2018-05-31 组件见传参的坑

2018-05-31  本文已影响0人  remix_huang

好了 终于逃不过要搞组件间参数传递 这是我在学习vue时候非常头疼的一个问题。由于Vue 2.x以后相比较Vue 1.x而言,升级变化除了实现了Virtual-Dom以外,给使用者最大不适就是移除的组件的props的双向绑定功能。
之前在Vue1.x中利用props的twoWay和.sync绑定修饰符就可以实现props的双向绑定功能,但是在Vue2中彻底废弃了此功能,似乎需要双向绑定可以自己来实现。不过人家既然废除了,肯定有其中的道理,想传参就单向通信吧。

先来看个代码片段:


引入组件 然后components里注册一下
//父组件中
<sitelist :site-id="dialogForm.data.site_id" v-on:listenToChildEvent="siteWatch"
                  class="componentItem"></sitelist>
//子组件中
<template>
  <el-form-item label="场地列表">
    <el-select v-model="siteId" placeholder="请选择场地">
      <el-option v-for="(item, index) in sitedata" :key="index" v-bind:label="item.title_cn" v-bind:value="item.site_id"></el-option>
    </el-select>
  </el-form-item>
</template>


<script type="es6">
import {site} from '@/api/general'

export default{
  props: ['siteId'],
  data() {
    return {
//以上通过props接收父组件传过来的siteid 要注意的是 父组件中的写法是 xxx-xxx 加横线分隔 在子组件中接收需要用xxxXxx的驼峰方式接收。

其实也很简单的一个功能 就是把所有能选择的场地都封装一下↓


页面中
当我选择子组件的select时... wtf?!

找来找去 原来问题出在这里了↓

//子组件中html
<el-select v-model="componentSite" placeholder="请选择场地"> ←就是这个v-model
      <el-option v-for="(item, index) in sitedata" :key="index" v-bind:label="item.title_cn" v-bind:value="item.site_id"></el-option>
    </el-select>
//子组件中js
watch: {
    siteId: function (params) {
      this.componentSite = this.siteId;  //现在需要监听siteId的变化 换成这个componentSite放在v-model里 
    },
    componentSite: function(){
      this.$emit("listenToChildEvent", this.componentSite)
    }
  },

因为需要将父组件传来的值重新赋值 不能直接操作父组件传来的值


页面中

可以看到问题已经得到解决了。

关于作者


  var myproject = {

    nickName  : "remix_huang",

    site : "https://www.jianshu.com/u/717e2ca57b3f"

  }

上一篇 下一篇

猜你喜欢

热点阅读