关于VUE中组件之间传值

352次阅读
没有评论

关于 VUE 中组件之间传值

首先说 vue 组件之间传值有两种

一种是父组件传值到子组件 父 == > 子

另一种就是子组件传值到父组件 子 == > 父

基本都是利用了 vue 中的 props

首先看一下父传子

父组件的代码是 App.vue

<template>
  <div id="app">
    <TestVue msg="Welcome to Your Vue.js App" />
  </div>
</template>

<script>
import TestVue from './components/TestVue.vue'
export default {
  name: 'App',
  components: {TestVue}
}
</script>

子组件的代码是 TestVue.vue

<template>
<div>
    <input :value="msg" >
</div>
</template>
<script>
export default{
    props: [
        "msg"
    ]
}
</script>

这里很顺利的把 msg 给传递到了子组件那里

下面是效果图

关于 VUE 中组件之间传值

这里说一下,props 有两种接收对象的方法,一种是使用对象{}

一种是使用 [], 注意使用[] 接收到时候注意使用双引号包裹好

第二种传递是子组件传值到父组件

这里需要事先父组件先传递一个函数到子组件中

然后子组件通过调用这个函数实现传递数值的目的

父组件代码 App.vue

<template>
  <div id="app">
    <TestVue :getName="getName" />
  </div>
</template>

<script>
import TestVue from './components/TestVue.vue'
export default {
  name: 'App',
  components: {TestVue},
  methods:{getName(name){console.log(name)
    }
  }
}
</script>

子组件代码 TestVue.vue:

<template>
<div>
    <button @click="sendName"> 点我传递数据 </button>
</div>
</template>
<script>
export default{data(){
        return {name: "testName"}
    },
    props: [
        "getName"
    ],
    methods: {sendName(){this.getName(this.name)
        }
    },
}
</script>

关于 VUE 中组件之间传值

其中子传父中其实还可以使用更加灵活的 $emit 去传值

父组件的代码 App.vue

<template>
  <div id="app">
    <TestVue @zdy="getName" />
    <p>{{childData}}</p>
  </div>
</template>

<script>
import TestVue from './components/TestVue.vue'
export default {
  name: 'App',
  components: {TestVue},
  data() {
    return {childData:""}
  },
  methods:{getName(name){this.childData = name}
  }
}
</script>

子组件的代码 TestVue.vue:

<template>
<div>
    <button @click="sendName">点我传递数据 </button>
</div>
</template>
<script>
export default{data(){
        return {name: "testName"}
    },
    methods: {sendName(){this.$emit("zdy",this.name)
        }
    },
}
</script>

关于 VUE 中组件之间传值
正文完
 
评论(没有评论)