【问题标题】:vue2.js component vmodel passing datavue2.js 组件 vmodel 传递数据
【发布时间】:2017-04-20 08:32:40
【问题描述】:

我对如何使用将 v-model 数据传递给组件有一点了解。

可以直接访问checkbox模型数据还是需要通过props传入组件?

如果有人用代码解释或指出对我有帮助的地方?

我的 HTML

  <template id="my-child">

    <tr>
      <td >{{ item.title }}</td>
      <td style="padding:20px" v-for="price in item.prices"   v-bind:price="price" >{{ price }}</td>
    </tr>
  </template>


    <template id="my-parent">

      <div class="box" >
          <div v-for="item in items">
            <h1>{{ item.name }}</h1>
                <img :src="item.imageUrl" style="width:200px;">
                <p>{{item.extract}}</p>
                {{ item.holidayType }}

                  <div is="task" v-for="avail in item.avail"   v-bind:item="avail"  >

                  </div>    


          </div>
      </div>

    </template>

   <div id="root">
      <div id="homesFilters">


          <input type="checkbox" id="1" value="hottub" v-model="test"> hot tub
          <input type="checkbox" id="2" value="garden" v-model="test"> garden
          <input type="checkbox" id="3" value="cottage" v-model="test"> cottage
      </div>

       <task-list></task-list>
    </div>

我的代码

Vue.component('task-list', {
  template: '#my-parent',
  props: ['test'],
  data: function() {
        return {
            items: [],

        }
  },
  methods: {
    getMyData: function(val) {

      console.log(this.test);

        var _this = this;
        $.ajax({
            url: 'vuejson.php',
            method: 'GET',
            success: function (data) {

                _this.items = data;
            },
            error: function (error) {
                alert(JSON.stringify(error));
            }  
        })

     }
  },
  mounted: function () {
       this.getMyData("0");
    }
});

Vue.component('task', {

  template: '#my-child',
  props: ['item'],

    data: function() {
        return {

        }
    }
});


new Vue({
  el: "#root",
  data: {
      test:[]
  },

});

</script>

【问题讨论】:

    标签: javascript vue.js vuejs2


    【解决方案1】:

    我用您的代码(和模拟数据)编写了一个快速代码笔:https://codepen.io/tuelsch/pen/RVrXbX?editors=1010

    要访问父组件上的复选框值test,您可以将其作为道具传递给父组件,如下所示:

    <task-list v-bind:test="test"></task-list>
    

    这样,组件将始终保持最新状态。在我的 codepen 中,我将值打印到页面以说明这种行为。

    如果您的应用程序变得更大,您可能需要考虑使用像 vuex https://vuex.vuejs.org/en/ 这样的通量模式来存储您的过滤器值并从您的组件中访问它们。

    【讨论】:

    • 太好了,您可以通过这种方式将尽可能多的变量绑定到组件?我会看vuex
    • root: {{test}} 只是一种快速而肮脏的方法,可以检查此范围内的测试内容是什么,并查看当您选中/取消选中过滤器时它如何变化。 Vue 非常友好地以人类可读的方式打印数组。
    • 您可以将任意数量的道具传递给子组件:vuejs.org/v2/guide/components.html#Props
    • 所以在组件内我现在可以访问 this.test?
    猜你喜欢
    • 2018-08-11
    • 2020-10-07
    • 2016-09-24
    • 2018-03-06
    • 2019-01-04
    • 2021-09-07
    • 1970-01-01
    • 2021-08-20
    相关资源
    最近更新 更多