My initial experience with vue.js has been complicated by issues with routers

I've recently dipped my toes into the world of Javascript and vue.js.

After following a tutorial on creating a single page shopping application, I decided to incorporate routers into my learning project.

However, I encountered some interesting errors in the console.

Could someone guide me through where I might be going wrong?

This is how my index.html looks:

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id = "app">
        <h1>Shopping Cart</h1>
        <ul>
            <li v-for="item in shoppingCart">
                {{ item.label }} {{ item.cost }} euros
                <a href="#" @click="addItem(item)"> {{ isSelected(item) }} </a>
            </li>
            <p>total = {{ getTheTotal }} euros</p>
        </ul>
        <li v-for="item in shoppingCart">
            <router-link to="item.link"><img v-if= "item.selected == true"width="150" height="100" :src="item.url"></img></router-link>
        </li>
        <router-view></router-view>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
    <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
    <script src = "vue.js"></script>
</body>
</html>

And this is my vue.js file:

const Bananas = { template: '<div>in bananas</div>' }
const Apples = { template: '<div>in apples</div>' }
const Pears = { template: '<div>in apples</div>' }
const Cars = { template: '<div>in apples</div>' }

const router = new VueRouter ({
    routes: [
        { path: '/bananas', component: Bananas },
        { path: '/apples', component: Apples },
        { path: '/pears', component: Pears },
        { path: '/cars', component: Cars }
    ]
})

const app = new Vue ({
    el: "#app",
    data: {
        shoppingCart: [
            { label: "Apples", cost: 2, selected: false, url: 'https://i2.wp.com/ceklog.kindel.com/wp-content/uploads/2013/02/firefox_2018-07-10_07-50-11.png', link: "/apples" },
            { label: "Pears", cost: 3, selected: false, url: 'https://post.healthline.com/wp-content/uploads/2018/11/10617-Do_You_Have_a_Pear_Allergy-_732x549-thumbnail.jpg', link: "/pears" },
            { label: "Bananas", cost: 5, selected: false, url: 'https://media.lactualite.com/2014/08/banane.jpg',link: "/bananas" },
            { label: "Cars", cost: 5000, selected: false, url: 'https://specials-images.forbesimg.com/imageserve/5d3703e2f1176b00089761a6/960x0.jpg?cropX1=836&cropX2=5396&cropY1=799&cropY2=3364', link: "/cars" }
        ]
    },
    computed: {
        getTheTotal() {
            let rez = 0

            this.shoppingCart.forEach(element => {
                if (element.selected == true) {
                    rez += element.cost
                }
                console.log(rez)
            })
            return rez
        }
    },
    methods: {
        addItem: function(item) {
            if (item.selected == false)
                item.selected = true
            else if (item.selected == true)
                item.selected = false
        },
        isSelected: function(item) {
            if (item.selected == true)
                return ("remove")
            if (item.selected == false)
                return ("add")
        }
    }
}).$mount('#app')

Here are the errors I'm facing:

[Vue warn]: Error in render: "TypeError: Unable to get property 'matched' of undefined or null reference"

(found in <Root>)

TypeError: Unable to get property 'matched' of undefined or null reference

[Vue warn]: Cannot find element: #app

[Vue warn]: Error in render: "TypeError: Unable to get property 'matched' of undefined or null reference"

(found in <Root>)

TypeError: Unable to get property 'matched' of undefined or null reference

As a result, the page isn't displaying anything anymore.

Your assistance is greatly appreciated! :)

Since I'm also new to stack overflow, please feel free to provide feedback if my post isn't presented correctly.

Answer №1

It seems like you forgot to include the router object in your new Vue call, causing the app to be unaware of the router and routes:

const app = new Vue ({
  router,         // ✅ Add this
  el: "#app",
  ...
});

Additionally, make sure to use a : binding on the <router-link> to attribute like so:

<router-link :to="{ path: item.link }">
  <img v-if="item.selected" width="150" height="100" :src="item.url">
</router-link>

Remember to correct your data as well (3 out of 4 references say "apples"):

const Bananas = { template: '<div>in bananas</div>' }
const Apples = { template: '<div>in apples</div>' }
const Pears = { template: '<div>in pears</div>' }
const Cars = { template: '<div>in cars</div>' }

Answer №2

In order to properly set up the Vue router, make sure to use the Vue.use(router) method before creating your Vue instance.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble deleting JavaScript object properties within a loop?

Struggling to comprehend the behavior of this particular piece of javascript code. const devices = searchResult.results.forEach(device => { const temp = Object.keys(device.fields); for(var property in temp) { if(device.fields.hasOwnPro ...

Update the URL path with the selected tab item displayed

Is there a way to show the selected tab item in the URL path? I came across this example using Material UI: import * as React from 'react'; import Tabs from '@mui/material/Tabs'; import Tab from '@mui/material/Tab'; import Typ ...

Using ReactJS to dynamically change styles based on state variables can sometimes cause CSS

Currently delving into the world of React. Learning about states/props and the art of dynamically altering elements. I've set up the component states like this: constructor(props) { super(props); this.modifyStyle = this.modifyStyle.bind(thi ...

Can Jquery mobile detect drag gestures?

Is there an event in Jquery Mobile that allows you to hide/show a div by dragging it, similar to the effect seen on phones? I have searched on different platforms and found that using Jquery UI is the closest solution. Is it possible to achieve this only ...

Run a function continuously while a key is being held down

I am currently working on a Javascript program that will move a div up and down based on key inputs. The idea is to continuously update the 'top' style value of the div while a specific key is pressed. While the basic function works, I am struggl ...

Is it possible for a hybrid app using Angular 7/1.x to enable Hot Module Replacement (H

Having trouble implementing HMR on a hybrid Angular application using the downgradeModule strategy. I previously sought help from a similar question on Stack Overflow Can an Angular 5/1.x hybrid app support HMR? but didn't find a satisfactory answer. ...

Store <td> in a variable

At the moment, I have a script that allows users to input an item name, along with its size, color, and other options. Each of these entries is saved as individual items with their custom specifications, such as a black t-shirt in large size. The script c ...

Using jQuery sortable with the overflow property set to hidden to sort items between two lists

I need help with a jQuery sortable feature where I have two lists and can move items between them: $( '#productsList, #orderList' ) .sortable({connectWith: '.containerDiv'}) .disableSelection(); My issue arises when I try to implement ...

Encountering a type mismatch error in Typescript while working with Redux state in a store file

It appears that I have correctly identified all the types, but could there be a different type of Reducer missing? 'IinitialAssetsState' is not assignable to type 'Reducer' The complete error message: Type '(state: { assets: n ...

Access the filtered data with Vuex and Firestore to display the results

I am looking to enhance my project by implementing a filtering feature. I currently have a buttons component that will trigger the filter search. When I click the restaurant button, it should display the shops with a "Restaurant" value in Firestore. Conv ...

Create a d.ts file for Vue components that are written using Typescript

As a newcomer to Vue, I am eager to dive into creating components and publishing packages to NPM. My plan is to develop Vue (typescript) + Vuetify reusable components that can be easily installed from NPM into any of my projects. While I have successfully ...

What is the recommended TypeScript type for the NextJS _app.tsx Component and pageProps?

Take a look at the default _app.tsx code snippet from NextJS: function MyApp({ Component, pageProps }) { return ( <Component {...pageProps} /> ) } The issue arises when transitioning to TypeScript, as ES6Lint generates a warning indicating t ...

Update the DIV element's class to reflect whether the quiz answer provided is correct or incorrect

I am facing a challenge while attempting to assign a CSS class to a dynamically created element in JavaScript. The error I'm encountering pertains to the reference issue with the trackerMarker element within the event listener functionality. Although ...

What methods can be used to block the input of non-numeric characters in a text field?

I stumbled upon this particular inquiry. Although, the majority of responses involve intercepting key presses, checking the key code, and halting the event if it does not match an acceptable key code. However, there are some issues with this approach. ...

How to pass and display a $_GET variable using PHP load file with JavaScript

After encountering an issue with passing a GET variable from index.php to included.php file (loaded by javascript), I came across a helpful solution using the PHP require function on Stack Overflow. In my situation, I had the following code: // for index ...

Guide on retrieving the value of "form" from a select using jQuery in a Ruby on Rails application

I am struggling to figure out how to use jQuery to pass the value of the form attribute from the select tag. I have been trying different ways, but so far haven't been successful. When using simple_form_for, the input statement looks like this: < ...

Receiving JSON objects from Javascript in Django Views

When I attempt to pass a Json Object value from making an API call to my views.py in Django template, I encounter difficulty retrieving the value after an ajax call. let application = JSON.parse(sessionStorage.getItem("appId")); let kycStatus = a ...

Guide on adjusting the value for a Bootstrap slider

Using the bootstrap slider, I am trying to configure a way to assign a value to the handle from another variable. Although I came across a method that uses the data-slider-value attribute for this purpose, it did not work for me. <input id="gravite" na ...

Discover the trick to capturing the back button and dynamically refreshing the webpage with ajax!

I am currently facing an issue with a dynamically updating web page where I need the browser's "back" button to trigger a function for refreshing data instead of navigating back a page. I have managed to trap the "back" button using the following code ...

Tips for displaying user data from a mongodb database on a webpage, making edits to the information, and then saving the updated data

I have a website where users can register, log in, and update their profile information. However, I am facing an issue where only the data of the first user in the database table is being retrieved. How can I get the data of the currently logged-in user? ...