我在上一篇说了一下父子组件之间是如何传值的,今天说一会儿组件若是须要改变传过来的数据供本身使用。javascript
在 App.vue 中html
<template> <div class="hello"> <h3>我是 App 父组件</h3> <h4>访问本身的数据:{{msg}},{{name}},{{user.id}}</h4> <hr> <!-- 1. 在调用子组件时,绑定想要获取的父组件中的数据 --> <Hello :message="msg"></Hello> </div> </template> <script> // 引入 Hello 组件 import Hello from './assets/components/Hello.vue' export default { data(){ return { msg:'父组件', name:'tom', age:'22', user:{ id:1234, userName:'Jack' } } }, // 注册 Hello 组件 components:{ Hello } } </script>
在 Hello.vue 中vue
<template> <div class="hello"> <h3>我是 hello 子组件</h3> <!-- 在页面中直接渲染便可 --> <h4>访问父组件中的数据: {{msg}}</h4> <button @click="change">改变父组件的数据</button> </div> </template> <script> export default { // 2. 在子组件内部,使用 props 选项声明获取的数据,即接收来自父组件中的数据 props:['message'], data(){ return { // 定义一个局部变量,并用 props 的值来初始化它 msg:this.message } }, methods:{ // 定义一个方法,来触发改变父组件的数据 change(){ this.msg = '我改变了父组件的数据' } } } </script>
效果图:java
在 Hello.vue 中改动数组
<script> export default { // 2. 在子组件内部,使用 props 选项声明获取的数据,即接收来自父组件中的数据 props:['message'], data(){ return { // 定义一个局部变量,并用 props 的值来初始化它 msg:this.message } }, computed:{ // 定义一个方法,来触发改变父组件的数据 change(){ return this.msg = '我改变了父组件的数据' } } } </script>
当页面渲染成功自动完成计算ide
在 App.vue 中把 template 的内容更改成ui
<template>
<div class="hello"> <h3>我是 App 父组件</h3> <h4>访问本身的数据:{{msg}}</h4> <hr> <!-- 1. 在调用子组件时,绑定想要获取的父组件中的数据 --> <!-- .sync 会被扩展为一个自动更新父组件属性的 v-on 监听器 --> <Hello :message.sync="msg"></Hello> </div> </template>
在 Hello.vue 中更改成this
<template> <div class="hello"> <h3>我是 hello 子组件</h3> <!-- 在页面中直接渲染便可 --> <h4>访问父组件中的数据: {{message}}</h4> <button @click="change">改变父组件的数据</button> </div> </template> <script> export default { // 2. 在子组件内部,使用 props 选项声明获取的数据,即接收来自父组件中的数据 props:['message'], methods:{ change(){ // 使用 .sync 时,须要显式的触发一个更新事件 // update 为固定写法,后面跟将要被改变的数据对象,接着写替换的数据 this.$emit('update:message','我改变了父组件的数据') } } } </script>
效果为:spa
在 App.vue 中code
<template> <div class="hello"> <h3>我是 App 父组件</h3> <h4>访问本身的数据:{{user.userName}}</h4> <hr> <!-- 2. 在调用子组件时,绑定想要获取的父组件中的数据 --> <Hello :user="user"></Hello> </div> </template> <script> // 引入 Hello 组件 import Hello from './assets/components/Hello.vue' export default { data(){ return { // 1. 在父组件中把数据写成对象的形式 user:{ id:1234, userName:'Jack' } } }, // 注册 Hello 组件 components:{ Hello } } </script>
在 Hello.vue 中
<template> <div class="hello"> <h3>我是 hello 子组件</h3> <!-- 5. 在页面中直接渲染便可 --> <h4>访问父组件中的数据: {{user.userName}}</h4> <button @click="change">改变父组件的数据</button> </div> </template> <script> export default { // 3. 在子组件内部,使用 props 选项声明获取的数据,即接收来自父组件中的数据 props:['message','user'], methods:{ // 4.直接修改 user 对象中的数据 change(){ this.user.userName = 'Tom' } } } </script>
效果以下:
今天的分享就到这里,若有不足,欢迎留言讨论