财产约束&在vue.js中同步

时间:2016-12-05 20:11:25

标签: vue.js

我在vue.js中同步我的属性时遇到问题,我有一个活跃的'我想要设置为每个实例的值的属性' plan',但同时我想将该属性与父级同步,没有运气。我做错了什么?

<!DOCTYPE html>
<html lang="en">
 <head>
    <title>Bootstrap Vue</title>
    <link rel="stylesheet prefetch" href="http://bootswatch.com/paper/bootstrap.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.3/vue.js"></script>
</head>
<body>
  <div class="container">
      <div id="app">
        <pre>
          @{{ $data | json}}
        </pre>
        <div v-for="plan in plans">
          <plan :active.sync="active" :plan.sync="plan"></plan>
        </div>
      </div>
  </div>

  <template id="plan_template">
      <div>
        <span >@{{ plan.name }}</span>
        <span >@{{ plan.price }}/month</span>
        <button @click="setActivePlan" class="btn btn-primary btn-xs">UPGRADE</button>
      </div>
  </template> 

  <script>
    new Vue({
      el:'#app',
      data:{
        plans:[
          {name:'Executive',price:100},
          {name:'Professional',price:50},
          {name:'Personal',price:30},
          {name:'Free',price:0}
        ],
        active:{},

      },

      components:{
        plan:{
          template:'#plan_template',

          props:['plan', 'active'],

          methods:{
            setActivePlan:function(){
              this.active=this.plan;
            }
          }
        }
      }
    });
  </script>
</body>
</html>

1 个答案:

答案 0 :(得分:-1)

注意:这个答案适用于Vue JS的V2,&lt; 2.3.0。

如果您正在使用V2.3.0 +,则可以使用.sync.once修饰符:documentation here

您正在使用Vue的第2版。 .sync.once修饰符已被删除。来自docs

  

道具现在总是单向下降。要在父作用域中产生副作用,组件需要显式发出事件而不是依赖于隐式绑定。

我已修改您的代码以在此处使用事件:

new Vue({
  el:'#app',
  data:{
    plans:[
      {name:'Executive',price:100},
      {name:'Professional',price:50},
      {name:'Personal',price:30},
      {name:'Free',price:0}
    ],
    active:{},
  },
  methods: {
    setActivePlan: function(plan) {
      this.active = plan;
    }
  },

  components:{
    plan:{
      template:'#plan_template',

      props:['plan', 'active'],

      methods:{
        setActivePlan:function(){
          // emit an event to the parent indicating that this is the active plan
          this.$emit('activate-plan');
        }
      }
    }
  }
});
<link rel="stylesheet prefetch" href="http://bootswatch.com/paper/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.3/vue.js"></script>

<div class="container">
  <div id="app">
    <div v-for="plan in plans">
      <plan :plan="plan"
            :active="active"
            @activate-plan="setActivePlan(plan)"
            >
      </plan>
    </div>
    <pre>
      {{ JSON.stringify($data, null, 2) }}
    </pre>
  </div>
</div>

<template id="plan_template">
  <div>
    <span >{{ plan.name }}</span>
    <span >{{ plan.price }}/month</span>
    <button @click="setActivePlan" class="btn btn-primary btn-xs">UPGRADE</button>
  </div>
</template>