Vue2 v-bind在子实例上无法正常工作?

时间:2017-11-03 14:39:35

标签: vue.js vuejs2

我有一个Vue的子实例,v-bind仅适用于父实例,但不适用于子实例。我做了一个示例文件来解释我的问题。

我错过了什么吗?

这是我的代码:

var app2 = new Vue({
  el: '#app2',
  data: {
    isSpinning2: true
  },
  methods: {
    stop2: function() {
      app2.isSpinning2 = false;
    }
  }
});

var app1 = new Vue({
  el: '#app1',
  data: {
    isSpinning: true
  },
  methods: {
    stop1: function() {
      app1.isSpinning = false;
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.2/vue.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<div id="app1">
  <i v-bind:class="{'fa-spin': isSpinning}" class="fa fa-address-book"></i>
  <button v-on:click="stop1">Stop 1</button>
  <div id="app2">
    <i v-bind:class="{'fa-spin': isSpinning2}" class="fa fa-address-book"></i>
    <button v-bind:onclick="stop2">Stop 2</button>
  </div>

</div>

1 个答案:

答案 0 :(得分:0)

这正是组件的用途。这是一个封装你的微调器按钮的组件。

console.clear()

Vue.component("spinner",{
  template: `
    <div>
      <i v-bind:class="{'fa-spin': isSpinning}" class="fa fa-address-book"></i>
      <button v-on:click="stop"><slot /></button>  
    </div>
  `,
  data(){
    return {
     isSpinning: true
    }
  },
  methods: {
    stop: function() {
      this.isSpinning = false;
    }
  }
})


var app1 = new Vue({
  el: '#app1',
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.2/vue.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<div id="app1">
  <spinner>Stop 1</spinner>
  <spinner>Stop 2</spinner>
</div>