javascript - vue2.js 组件 vmodel 传递数据

标签 javascript vue.js vuejs2

我缺少对如何将 v-model 数据传递给组件的理解。

我可以直接访问复选框模型数据还是需要通过 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>

最佳答案

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

要访问父组件上的复选框值 test,您可以像这样将它作为 prop 传递给父组件:

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

这样它在组件上将始终是最新的。在我的代码笔中,我将值打印到页面以说明此行为。

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

关于javascript - vue2.js 组件 vmodel 传递数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43514229/

相关文章:

javascript - 动态添加具有特定类名称的表单元格

javascript - 无法使用Vue.js从opendweathermap获取天气数据

javascript - 使用 Lodash 查找 [] 数组内 JSON 数组的索引

vue-component - 从 VueJS 中的 v-for 中删除重复元素

Vue.js 自定义事件命名

javascript - 如何使用 Hooks 将状态从 child 传递给 parent

javascript - 获取站点域名并拆分为两个变量

javascript - Vue.js 组件中的动态值

javascript - Aframe + vuejs - 核心 :schema:warn Unknown property `color` for component/system `undefined` . +10ms aframe.js:327

javascript - 访问 javascript 对象的实例变量