1.子组件向父组件动态传值和静态传值
1.父组件
<template> <view class=""> <!-- :title="title" 这是动态传值 ,content="this.content" content="这里面是写死的字符串,无法获得data中content的值(内容1)"这是静态传值 --> <mycomponent :title="title" content="this.content" @tap2="tap"></mycomponent> </view> </template> <script> import mycomponent from "@/components/mycomponent.vue" export default { data() { return { title : "新闻标题", content:"内容1" } }, onLoad:function(){ var _self = this; setTimeout(function() { _self.title = "hi123" }, 3000); }, methods:{ tap : function (e) { console.log("父组件tap方法") } }, components: { mycomponent } } </script> <style lang="less"> @import "../../less.less"; </style>
2.子组件
<template> <view> <!-- 此处动态获得父组件中的data中title的值"内容1",动态传值父组件通过属性绑定的方式 --> <h1 @click="tap1">{{title}}</h1> <!-- 此处无法动态获得父组件中的data中content的值"内容1" --> <div>{{content}}</div> </view> </template> <script> export default { props:{ title : { type : String, default : "" }, content : { type : String, default : "" } }, data() { return { }; }, watch:{ title : function (newVal, oldVal) { console.log(newVal, oldVal); } }, methods:{ tap1 : function(){ console.log("子组件内部方法tap1"); this.$emit('tap2', this.title) }, tap2:function(){ console.log("方法tap2"); } } } </script> <style> </style>
效果图: