Vue2进阶篇-ref属性、props属性、mixin混入、plugin插件

Vue2基础全套教程合集:点击跳转        Vue2高级全套教程合集:点击跳转


一、ref属性

  1. 被用来给元素或子组件注册引用信息(id的替代者)
  2. 应用在html标签上获取的是真实DOM元素,应用在组件标签上是组件实例对象(vc)
  3. 使用方式:
    1. 打标识:<h1 ref="xxx">.....</h1><School ref="xxx"></School>
    2. 获取:this.$refs.xxx

代码示例:

<template>
	<div>
		<h1 v-text="msg" ref="title"></h1>
		<button ref="btn" @click="showDOM">点我输出上方的DOM元素</button>
		<School ref="sch"/>
	</div>
</template>

<script>
    //引入School组件
    import School from './components/School'

    export default {
        name: 'App',
        components: {
            School
        },
        data() {
            return {
                msg: '欢迎学习Vue!'
            }
        },
        methods: {
            showDOM() {
                // ref用于获取DOM元素而产生的,$refs上收集了所有在DOM元素上加了ref属性的DOM元素
                // ref与id的区别:获取组件时,ref获取的是组件的实例对象vc,而id是组件的div的DOM对象
                console.log(this.$refs.title) //真实DOM元素
                console.log(this.$refs.btn) //真实DOM元素
                console.log(this.$refs.sch) //School组件的实例对象(vc)
            }
        },
    }
</script>

二、props属性

  1. 功能:让组件接收外部传过来的数据

  2. 传递数据:<Demo name="xxx"/>

  3. 接收数据:

    1. 第一种方式(只接收):props:['name']

    2. 第二种方式(限制类型):props:{name:String}

    3. 第三种方式(限制类型、限制必要性、指定默认值):

      props:{
          name:{
          type:String, //类型
          required:true, //必要性
          default:'老王' //默认值
          }
      }
      

      备注:props是只读的,Vue底层会监测你对props的修改,如果进行了修改,就会发出警告,若业务需求确实需要修改,那么请复制props的内容到data中一份,然后去修改data中的数据。

代码示例:

<template>
	<div>
		<h1>{{msg}}</h1>
		<h2>学生姓名:{{name}}</h2>
		<h2>学生性别:{{sex}}</h2>
		<h2>学生年龄:{{myAge+1}}</h2>
		<button @click="updateAge">尝试修改收到的年龄</button>
	</div>
</template>

<script>
	export default {
		name:'Student',
		data() {
			console.log(this)
			return {
				msg:'我是一个尚硅谷的学生',
				myAge:this.age
			}
		},
		methods: {
			updateAge(){
				this.myAge++
			}
		},
		//一、简单声明接收
		// props:['name','age','sex'] 

		//二、接收的同时对数据进行类型限制
		/* props:{
			name:String,
			age:Number,
			sex:String
		} */

		//三、接收的同时对数据:进行类型限制+默认值的指定+必要性的限制
		props:{
			name:{
				type:String, //name的类型是字符串
				required:true, //name是必要的
			},
			age:{
				type:Number,
				default:99 //默认值
			},
			sex:{
				type:String,
				required:true
			}
		}
	}
</script>

三、$attrs$listeners

  1. 功能:
    • $attrs是收集父组件传递的所有参数(props已接收的不会收集);
    • $listeners是收集父组件传递的所有自定义事件。
  2. 使用方法:配合v-bindv-on使用

父组件AttrsListenersTest.vue

<template>
    <div>
        <h2>封装自定义按钮</h2>
        <!-- 当用户在使用我们封装的按钮时,需要想HintButton组件传递相应的参数 -->
        <HintButton type="success" icon="el-icon-delete" size="mini" title="提示按钮"></HintButton>
    </div>
</template>

<script>
import HintButton from "@/components/AttrsListenersTest/HintButton";
export default {
    name: 'AttrsListenersTest',
    components: {HintButton},
    data() {
        //这里存放数据",
        return {};
    },
}
</script>

子组件HintButton.vue

<template>
    <div>
        <a :title="title">
            <!-- v-bind 将所有$attrs属性绑定到el-button组件上。  v-on 将所有父组件传递的自定义事件绑定到子组件上 -->
            <el-button v-bind='$attrs' v-on="$listeners"></el-button>
        </a>
    </div>
</template>

<script>
export default {
    name: 'HintButton',
    props: ['title'],
    mounted() {
        // $attrs 专门用于捡props未收集的参数。
        console.log(this.$attrs)
        // $listeners 收集父组件传递的所有自定义事件
        console.log(this.$listeners)
    }
}
</script>

三、mixin混入

  1. 功能:可以把多个组件共用的配置提取成一个混入对象

  2. 使用方式:

    第一步定义混合:

       {
           data(){....},
           methods:{....}
           ....
       }
    

    第二步使用混入:

    ​ 全局混入:Vue.mixin(xxx)
    ​ 局部混入:mixins:['xxx']

代码示例:

mixin.js

export const hunhe = {
    methods: {
        showName() {
            alert(this.name)
        }
    },
    mounted() {
        console.log('你好啊!')
    },
};
// 混入的data和methods与组件中的冲突时,以组件为主
// 而生命周期等其他配置与组价你冲突时,则两边都执行,并不会覆盖 
export const hunhe2 = {
    data() {
        return {
            x: 100,
            y: 200
        }
    },
};

Student.vue

<template>
	<div>
		<h2 @click="showName">学生姓名:{{name}}</h2>
		<h2>学生性别:{{sex}}</h2>
	</div>
</template>

<script>
	// import {hunhe,hunhe2} from '../mixin'

	export default {
		name:'Student',
		data() {
			return {
				name:'张三',
				sex:'男'
			}
		},
		// mixins:[hunhe,hunhe2]
	}
</script>

四、plugin插件

main.js

//引入Vue
import Vue from 'vue'
//引入App
import App from './App.vue'
//引入插件
import plugins from './plugins'
//关闭Vue的生产提示
Vue.config.productionTip = false

//应用(使用)插件
Vue.use(plugins,1,2,3) // 此处对应install的参数列表
//创建vm
new Vue({
	el:'#app',
	render: h => h(App)
})

plugin.js

export default {
    install(Vue, x, y, z) {
        console.log(x, y, z);
        //全局过滤器
        Vue.filter('mySlice', function(value) {
            return value.slice(0, 4)
        })

        //定义全局指令
        Vue.directive('fbind', {
            bind(element, binding) {
                element.value = binding.value
            },
            inserted(element, binding) {
                element.focus()
            },
            update(element, binding) {
                element.value = binding.value
            }
        })

        //定义混入
        Vue.mixin({
            data() {
                return {
                    x: 100,
                    y: 200
                }
            }
        })

        //给Vue原型上添加一个方法(vm和vc就都能用了)
        Vue.prototype.hello = () => { alert('你好啊') }
        Vue.prototype.myMsg = '我的消息!'
    }
}

源代码出处:尚硅谷Vue2.0+Vue3.0全套教程丨vuejs从入门到精通

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值