//父组件App.vue
<Student name="张三" :age="18" sex="男" ref="stu"/>
//子组件Student.vue
props: ['name','age', 'sex'],
// props: {
// name: {
// type: String,
// required: true
// },
// age: {
// type: Number,
// default: 99
// },
// sex: {
// type: String,
// required: true
// }
// }
组件配置对象props:
- 简单接收:复用组件时,组件结构相同,但是组件的数据不一样,就可以在父组件中传递属性进去,子组件通过props以数组的形式接受数据;props:[‘属性名’,‘属性名’……]
- 对象形式接收:给每一个属性变量限定一个数据类型,限定接受数据的类型,这种props就必须写成一个对象,对象里面写props: {属性名:数据类型……}
- 接收时对数据进行多个设置:这样,接收的属性也是以一个对象的形式,props:{name:{type:类型,required:true(属性是否为必有项),default:值(默认值,不能和第二项一起使用,是单独使用的)}}
- 如果子组件的props中属性父组件并没有传递,那么该属性就会是undefined;父组件传递进来的数据子组件不能修改;、
- 子组件中:props接收进来的数据优先级比自己data的高,会先准备好props中的数据,然后再初始化data中的数据,所以在data里可以使用到props的数据;
//mixin.js混入
export const mixin = {
methods: {
showName() {
console.log(this.name);
}
}
}
export const mixin2 = {
data() {
return {
x: 1,
y: 2
}
}
}
//局部使用student.vue
import {mixin,mixin2} from '../mixin'
export default {
name: 'School',
data() {
return {
name: '某某学院',
sex: '新世纪',
x: 999
}
},
mixins: [mixin,mixin2]
//全局使用main.js
import Vue from 'vue'
import App from './App.vue'
import {mixin, mixin2} from './mixin'
Vue.config.productionTip = false
Vue.mixin(mixin)
Vue.mixin(mixin2)
new Vue({
el: '#app',
components: {
App
},
render: h => h(App)
})
组件配置项mixins混入:
- 多组件共有的东西,可以抽离到一个js文件中,然后通过暴露出来,在需要用的组件中使用mixins配置项来使用;mixins:[需要使用的混合,……]
- 混合就是复用组件配置;引入混合,就会将混合中有的内容和组件中的内容进行一个整合;对于组件的配置:混合和组件中都有的内容,会以组件中为准;对于生命周期来说,两者都会显示,只是混合中的在前面,组件中的在后面;
- 全局混合:在main.js入口文件进行引用混合,使用Vue.mixin(需要使用的混合),就可以在vue实例和它上面的组件和子组件都可以使用这个混合里的内容;
//插件plugins.js
export default {
install(Vue) {
Vue.mixin({
data() {
return {
x: 1,
y: 2
}
}
}),
Vue.prototype.hello = 'hello'
}
}
//App.vue
import plugins from './plugins'
Vue.use(plugins)
- 插件:1.定义:{install(Vue) {}}:(包含install方法的一个对象。对象.install = function)使用install一个函数定义,第一个参数Vue构造函数,后面可以自己定义参数;2.引入定义好的插件,只用import引入;3.应用插件,使用Vue.use(默认暴露的名字)来使用插件;有参数Vue就可以在插件中做全局配置,如全局过滤器、全局指令、全局混入、原型上添加属性或方法等等;
```css
/*Student.vue*/
<style lang="less" scoped>
.demo {
background-color: #af1;
.test {
color: aqua;
}
}
</style>
- 组件中的style样式汇总的时候会将所有样式汇总到一起,这样就会导致选择器命名相同的就会被覆盖掉,因此可以在style标签中写一个scoped(作用域),就表示该组件使用的是自己组件中的style;加上这个属性,vue就会给组件模板外层标签写一个特有属性,写样式的时候就会使用属性选择器;一般app组件上面不会添加该属性;
- style标签还有一个属性lang=“”可以用来调整自己写的是css还是less,但是脚手架不知此less需要安装less-loader包;
版权声明:本文为qq_50563868原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。