父组件传值子组件用Props
子组件传值父组件用$emit
父组件直接还可以直接取子组件的值用$refs
不建议使用会增加组件之间的耦合度,一般用于第三方插件的封装
ref如果绑定在dom节点上,拿到的就是原生dom节点。
ref如果绑定在组件上,拿到的就是组件对象,可以实现通信功能
父组件
- <template>
- <div>
- <button v-on:click="handelClick">打印看看button>
- <ChildModule ref="mychild">ChildModule>
- <input type="text" ref="myinput">
- <div type="text" ref="mydiv">wowodiv>
- div>
- template>
- <script>
- import ChildModule from "./components/ChildModule.vue" //导入ChildModule组件模板
- export default {
- inheritAttrs: false,
- data() {
- return {
-
- }
- },
- components: {
- ChildModule: ChildModule //注册局部子组件ChildModule:也可以写成ChildModule:ChildModule
- },
- methods: {
- handelClick() {
- console.log(this.$.refs.myinput);
- console.log(this.$.refs.mydiv);
- console.log(this.$.refs.mychild);
-
- this.$.refs.myinput.value="abc";
- this.$.refs.mydiv.style.background='red'; //
-
- this.$refs.mychild.user.name="李四"; //直接获取子组件的user.name值并重新赋值
- }
- }
- }
- script>
子组件
- <template>
- <div>
- {{user.name}}
- div>
- template>
- <script>
- export default {
- data(){
- return{
- user:{
- name:"张三",
- age:19,
- emial:"abc@123.com"
- }
- }
- },
- methods:{
-
- }
- }
- script>

我有三个组件关系如下:根组件app.vue中有一个AChild组件,AChild组件中有一个BChild组件
根组件app.vue
- <template>
- <div>
- <AChild>AChild>
- div>
- template>
- <script>
- import AChild from "./components/AChild.vue" //导入AChild组件模板
- export default {
- inheritAttrs: false,
- data() {
- return {
- name: "我是根组件name"
- }
- },
- components: {
- AChild
- },
- methods: {
- }
- }
- script>
AChild组件
- <template>
- <div>
- <BChild>BChild>
- div>
- template>
- <script>
- import BChild from "./BChild.vue" //导入BChild组件模板
- export default {
- inheritAttrs: false,
- data() {
- return {
- name: "我是A组件name"
- }
- },
- components: {
- BChild
-
- },
- methods: {
-
- }
- }
- script>
BChild组件
- <template>
- <div>
- <button @click="handelClick">点我button>
- div>
- template>
- <script >
- export default{
- inheritAttrs:false,
- methods:{
- handelClick(){
- console.log( this.$parent.name); //获取父组件的name
- console.log( this.$parent.$parent.name); //获取父组件的父组件的name
- console.log( this.$root.name); //获取根组件的name(这个直接取最上级组件的值)
- }
- }
- }
- script>