VueJS ReferenceError: bookz is not defined

89 views Asked by At

I have a problem that when I assign a variable in the correct way in .js file with Vue js format and in the html file when I try to use it I get ReferenceError: bookz is not defined. Before I have written the exact same thing as in <script> tags, it was working. But now with this new variable it cannot run. In addition, when I use the old variable with different data it still shows the previous data.

VueJS part

const app = new Vue({
 data: {
    bookz: [
            {id:1 , title: "AAAA"},
            {id:2 , title: "BBBB"},
            {id:3 , title: "CCCC"},
           ],
       }
}

HTML part

<select @change="onChange($event)" class="form-select form-control" v-model="bookz.title">
   <option>---Select a book---</option>
   <option v-for="b in bookz" v-bind:value="b.id">${b.title}}</option>
</select>   

I am trying to get a select with options from data in the vuejs part.

2

There are 2 answers

0
Ert51 On BEST ANSWER

I found what my mistake was. I simply forgot the to bind the Vuejs code with the HTML part, I added a div with class name of the el CSS selector in my Vue code and now it is working functionally. ( added the name in el:"#app" in Vue component into div class)

<div class="app">
      <select @change="onChange($event)" class="form-select form-control" v-model="bookz.title">
          <option>---Select a book---</option>
          <option v-for="b in bookz" v-bind:value="b.id">${b.title}}</option>
      </select>                                   
    </div> 

5
kissu On

You're probably looking for something like this

<template>
  <div>
    <p>selected: {{ selectedBook }}</p>
    <select v-model="selectedBook" class="form-select form-control">
      <option>---Select a book---</option>
      <option v-for="b in bookz" :key="b.id" :value="b.title">
        {{ b.title }}
      </option>
    </select>
  </div>
</template>

<script>
export default {
  data() {
    return {
      bookz: [
        { id: 1, title: 'AAAA' },
        { id: 2, title: 'BBBB' },
        { id: 3, title: 'CCCC' },
      ],
      selectedBook: '',
    }
  },
}
</script>

Here is a demo.