Encapsulate your own components
In daily development, we often use plug-in framework UI in Vue, which is very convenient. But how do we encapsulate our own defined components?Copy the code
steps
Create a custom component in main.js using the following code with the keyword installCopy the code
// Custom plug-in
const myplugin = { // is an object
install: function (Vue) {
// Do anything
console.log(Vue); }}// Use plugins
Vue.use(myplugin)
Copy the code
The following is an extension that uses custom plug-ins and mixins to create a form validation
Entry file app.vue
<template>
<div id="app">The user name<input type="text" v-model="name" />
<div>{{validate}}</div>
<router-view></router-view>
</div>
</template>
<script>
export default {
name: "app".data() {
return {
foo: 10.name: "Hahaha HHH".validate: "".// Verify the result
};
},
reles: {
foo: {
validate: (value) = > value > 1.Function (value){return value > 1}
message: "The variable must be greater than 1.",},name: {
validate: (value) = > value.length > 6.Function (value){return value! = = ""}
message: "Name attribute greater than 6 characters",}}};</script>
Copy the code
The main js to write
// The main.js plug-in form encapsulates a global blend
// Custom plug-in
const myplugin = { // is an object
install: function (Vue) {
// Do anything
// console.log(Vue);
Vue.mixin({ // Create a global blend
created() {
console.log(this.$options);
if (this.$options.reles) { //$option is used to get data and methods outside of data
// Check whether all pages have this rule
for (let key in this.$options.reles) {
// Get each value
const rule = this.$options.reles[key]
// Listen for changes in values
this.$watch(key, newValue= > { / / name / / new values
// Verify the result
console.log(key);
const reuslt = rule.validate(newValue) // The result is a Boolean
if(! reuslt) {this.validate = rule.message
} else {
this.validate = ""}})}}}})}}Copy the code