A, .vue file
<Template>
/ ** write html code here * /
<span>{{msg}}</span>
</template>
<script>
import { xxxx } from 'xxx'
export default {
// lifecycle hook
beforeCreate () {
},
created () {
},
beforeMount () {
},
mounted () {
},
beforeUpdate () {
},
updated () {
},
activated () {
},
deactivated () {
},
beforeDestroy () {
},
destoryed () {
},
Name: 'My-Component', // component tag
components: {// Here external components can be introduced, which template is then introduced using components
that Component1,
Component2
},
Model: {// v-model binding value the prop will be passed, if the internal component invokes this method, the value of v-model may change. Is not defined, then v-model attributes are value, is INPUT
prop: 'attribute name',
Event: 'method'
},
Data () {// Here define the properties of the component used inside can be used in the script with the template which , a region changed to a value where the two converted accordingly
return {
MSG: 'message',
allData: []
}
},
props: {// 这里是接收使用这个组件时,组件上面传入的属性
data: {
type: Array,
required: true,
default () {
return []
}
},
‘v-model使用的属性名’: {
type: Array,
required: false,
default () {
return []
}
},
},
watch: {// 监听属性的变化
data: {
deep: true,
handler (val, oldVal) {
if (val !== oldVal) {
this.allData = this.formatData({ data: val, parentId: 'root' })
this.$emit('v-model使用的方法', val)
}
}
},
},
computed: {// 计算属性,里面的属性的值变了的话,这个属性会跟着变
isShow() {
return !!this.msg
}
},
methods: {// 定义方法
toggle (isShow = false) {
this.isShow = isShow
},
formatData ({ data = [], parentId = '' } = {}) {
return true
},
},
mixins: [mixins],// 混入,mixins是vue实例对象的选项
directives: {/** 在template可以使用这里的指令,使用的时候在前面加一个v-,有钩子函数bind,unbind,inserted,update,componentUpdated。钩子函数的参数有如下例子,binding是一个对象包含name, value, oldValue, expression, args, modifiers */
focus: {
inserted: function (el, binding, vnode, oldVnode) {
el.focus()
}
}
},
filters: {在template可以使用这里的过滤器
capitalize (value) {
if (!value) {
return ''
}
value = value.toString()
return value.charAt(0).toUpperCase() + value.slice(1)
}
}
</script>
<style lang="less" scoped>
/** 这里可以写样式,scoped使得这里的样式不会影响别的地方,lang=less使得这里可以使用less预处理css*/
</style>
二、使用上面定义的组件
<my-component v-model="aa" data="cc"></my-component>
变量aa跟cc要在当前脚本定义属性。