当前位置: 代码迷 >> 综合 >> props,ref,emit,render使用
  详细解决方案

props,ref,emit,render使用

热度:2   发布时间:2023-12-22 10:43:50.0

注册时: :子组件=父组件属性或方法
1、在子组件获取父组件data值 props 格式:<组件名 :子组件props中变量=“父组件内容”></组件名t>

	<!--父组件向子组件传值,属性名称也需要使用- --><div id="app">	<my-component :parent-msg="msg"></my-component></div><template id="temp1"><div><!--经过测试,子组件无法直接获取父组件中的data--><div>{
   {title}}</div><div>{
   {parentMsg}}</div><button @click="changeMsg">修改</button></div></template><script type="text/javascript">var vue =new Vue({el:"#app",data:{	msg:'我是父组件中message'},components:{'my-component':{template:"#temp1",data(){return {title:'我是标题'}	},//props中的数据都是通过父组件传给子组件的//props中的数据都是只读的,无法直接赋值//props建议使用对象,并给每一个props声明类型和默认值props:{parentMsg:{type:String,defult:null}},methods:{changeMsg(){this.parentMsg="我被修改了"}	}}}})</script>

2、在组件里使用 this.$emit(组件自定义方法,参数) == 调用vue 里方法

	<div id="myvue"><!-- <button @click = "myClick">调用方法</button> --><com @mycomclick = "myshow"></com></div><template id = "mytempid"><div><!-- 组件中的单机事件,调用的不是vue中的methods,而是组件中的methods, --><!-- 调用组件内部按钮中的方法  单机-》组件中的methods->vue中的methods(必须自定义事件) --><button @click ="myClick">调用方法</button></div></template><script type="text/javascript">var com = {template:"#mytempid",data(){return {mymsg:'这是mycom组件中数据'}},methods:{myClick(){this.$emit("mycomclick","黄宇军");//调用myshow() = $emit()}}}var vm = new Vue({el: '#myvue',data: {},methods: {myshow(params){// alert(this.$refs.mydiv.innerText)alert("hello world!...终于出来了!" + params);// this.$refs.mycom.myComponentShow()},},components:{com}})</script>

3、在父组件引用子组件和自身的属性值和方法 ref refs使用

<div id="myvue"><!-- 普通元素 --><div ref = "mydiv">普通元素</div><!-- 组件 --><com ref = "mycom"></com><button @click ="myVueShow">调用组件中的方法</button></div><template id = "mytempid"><div>mycom组件</div></template><script type="text/javascript">var com = {template:"#mytempid",data(){return {mymsg:'这是mycom组件中数据'}},methods:{myComponentShow(){alert('这是mycom组件中方法')}}}var vm = new Vue({el: '#myvue',data: {},methods: {myVueShow(){// alert(this.$refs.mydiv.innerText)alert(this.$refs.mycom);// this.$refs.mycom.myComponentShow()},},components:{com}})</script>

4、render 渲染

	<div id="myvue"><div>这是div元素</div></div><template id = "mytempid"><span>mycom组件</span></template><script type="text/javascript">var com = {template:"#mytempid"}var vm = new Vue({el: '#myvue',data: {},methods: {},render:function(createElements){return createElements(com)//该参数可以将组件渲染成html}})</script>
  相关解决方案