vuejs在单击按钮时更新组件值不起作用

时间:2019-04-23 07:48:02

标签: vue.js vuejs2 vue-component

我有一个标头组件。单击按钮后,我无法更新标题组件的值

   <!DOCTYPE html>
     <html> 
      <head>
       <title>Page Title</title>
         </head>
        <body>
         <header>
         <my-component ref="foo"></my-component>
        </header>
           <div id="app">
           <h1>Component Test</h1>
          <button v-on:click="test">Button</button>
          </div>
     <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <script>
    var MyComponent = Vue.extend({
    template: '<div><p>Hello</p><div v-if="islogin">User</div></div>',
    data: function () {
      return {
        islogin: false
      };
    }
   });

var vm = new Vue({
  el: '#app',
  components: {
    'my-component': MyComponent
  },
  methods: {
    test: function () {         
      this.$refs.foo.islogin = true;
    }
  }
});


 </script>
</body>
</html>

我想在单击按钮时将islogin更新为true。现在,它显示“ TypeError:无法设置未定义的属性'islogin'”错误。

谢谢

2 个答案:

答案 0 :(得分:1)

您的组件“ my-component”不在Vuejs的范围内。 Vue位于ID为“ app”的div中。因此,您不能在此主要div之外添加其他组件

答案 1 :(得分:1)

将组件放入Vuejs #app范围内:

       <div id="app">
          <header>
             <my-component ref="foo"></my-component>
          </header>
          <h1>Component Test</h1>
          <button v-on:click="test">Button</button>
       </div>