简体   繁体   中英

Vue 2 data returned by component data function are not defined

I am developing an application and I am using Vue 2 as my javascript framework, I tried to declare some components and use them in my html pages this is my html:

<!DOCTYPE html>
<html>
<head>
  <title></title>
  <link rel="stylesheet"  
     href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.3.1/css/bulma.css"  />   
</head>
<body>

<div id="modal_element" >

<modal v-if="showModal" ></modal>

<button @click="showModal = true" >Show Modal</button>

</div>

<div id="root">
  <ul>
   <li v-for="task in incompeletedTasks" >
      {{ task.description }}
   </li>
  </ul>
</div>
</body>
<script src="https://unpkg.com/vue@2.1.10/dist/vue.js" ></script>
<script src="main.js"></script>    
<script src="modal.js" ></script>
<script>
   let main_data = {
     tasks : [
        { description : "Go to the store ", completed : true },
        { description : "Leave the store" , completed : false }
       ]        
    }
   new Vue({
     el : "#root",
     data : main_data,
     computed : {       
       incompeletedTasks() {
        return this.tasks.filter(task => !task.completed);
       }
   }
 });

and this the modal.js file:

Vue.component('modal',{
  template : '<div id="modal_element">
          <div class="modal is-active">
          <div class="modal-background"></div>
          <div class="modal-content box">
            <p>
              Some Modal Text here ...
            </p>
           </div>
          <button class="modal-close" @click="showModal = false" >
          </button>
       </div>',

   data : function(){
     return {
       showModal : false
     };
   }
  });

 new Vue({
  el : '#modal_element',
 });

but the modal is not displayed, and I am getting the following error in the chrome console

   [Vue warn]: Property or method "showModal" is not defined on the instance        
    but referenced during render. Make sure to declare reactive data 
    properties in the data option. 

Question : what modification do I have to make to get the code working? and html page successfully displays modal ?

I think there are a couple of things.

  1. You are creating 2 vue instances in this example (#root and #modal-element), so the data will not be able to be shared unless you have some store. Much better to have just a single instance and put components in that.
  2. You will need to pass the component into the vue instance in order for it to be aware of the component.

Here is an example with alot of the stuff trimmed out.

https://jsfiddle.net/Austio/vhgztp59/2/

The gist of it is

var component = ...createComponentStuff

new Vue({
  ...otherVueStuff,
  components: [component]
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM