Vue的传值方式(一)

106 阅读1分钟

//第一次写文章,把自己的理解说一说,后面会持续更新前端的文章,有错直接留言或者私信,我应届生

一、父组件向子组件传值

1、props

props用于父组件向子组件传递数据信息,传参方式是单向传输,只能父组件传给子组件,不能实现子组件传参给父组件.

简单来说,也就是在父组件上引入子组件,子组件例如div内需要显示,而这个数据是在父组件上得到的,例如分页器的total,你需要计算得到父组件的表单数据有多少条,再传进子组件然后显示出来。

props 着重于数据的传递,它并不能调用子组件里的属性和方法。像创建文章组件时,自定义标题和内容这样的使用场景,最适合使用prop。

子组件中

//son.vue
<template>
   <div class="child-container">
        接收父组件传递的值:{{ msgFromParent }}
   </div>
</template>

<script>
export default {
    // 接受父组件传递的数据
    props: ["msgFromParent"]
}
</script>

<style scoped>
</style>

父组件中

//parent.vue
<template>
    <div class="parent-container">
        父组件传递的值:{{ msg }}
        <!-- 通过自定义属性的方式,完成父组件中的数据传递给子组件使用 -->
        <Child :msgFromParent="msg"></Child>
    </div>
</template>

<script>
import Child from "./Child.vue"

export default {
    data() {
        return {
            msg: "parent data"
        }
    },
    components: {
        Child
    }
};
</script>

<style scoped>
.parent-container {
    width: 500px;
    height: 100px;
    background-color: rgb(235, 138, 138);
    color: #fff;
    font-size: 24px;
    text-align: center;
}
</style>

2、ref

在父组件使用子组件的时候使用ref绑定一个字符串,或者使用:ref动态绑定一个变量,然后在mounted中使用this.$refs.xxx.fn()初始化

ref用于数据之间的传递,如果ref用在子组件上能通过$ref获取到子组件节点、事件、数据、属性,主要还是父组件向子组件通信

$ref 着重于索引,主要用来调用子组件里的属性和方法,其实并不擅长数据传递。而且ref用在dom元素的时候,能使到选择器的作用,这个功能比作为索引更常有用到。

<template>
    <div>
        我是父组件
        <!-- 定义ref 获取子组件的属性和方法 -->
        <ChildrenVue ref='childrenRef' />
        <button @click="show">获取子组件的属性和方法</button>
    </div>
</template>
<script setup>
//引入子组件
import ChildrenVue from '../components/Children.vue';
import { ref } from 'vue'
//声明子组件的ref
const childrenRef = ref(null)
const show = () => {
    //使用子组件的属性和方法
    //通过 ref.value.子组件的属性or方法
    console.log(childrenRef.value.title);
    childrenRef.value.toggle()
}
</script>
<template>
    <div>
        我是子组件
    </div>
</template>
<script setup>
const title = '我是子组件的属性'
const toggle = () => {
    console.log('我是子组件的方法');
}
defineExpose({
    // 将想要暴露的属性和方法名称
    title, toggle
})
</script>

然后就是ref与$refs的结合使用(不能用来传值!!!)

直接通过this.$refs获取

//parent.vue
<template>
  <child ref="child"></component-a>
</template>
<script>
  import child from './child.vue'
  export default {
    components: { child },
    mounted () {
      console.log(this.$refs.child.name);  // JavaScript
      this.$refs.child.sayHello();  // hello
    }
  }
</script>
//child.vue
export default {
  data () {
    return {
      name: 'JavaScript'
    }
  },
  methods: {
    sayHello () {
      console.log('hello')
    }
  }
}