5. Definition and use of plug-ins
Basic writing
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<title>hello vue</title>
<! Vue library -->
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="root"></div>
</body>
<script>
// Plugnin plugin: also encapsulates versatility
// Define the plug-in
const myPlugin = {
install(app, options){
// This app is the root component. You can do a lot of things through app
console.log(app, options); }}const app = Vue.createApp({
template: `
`
});
app.component("my-title", {
template: `
hello world!
`
});
// Using the plug-in, arguments can be passed in
app.use(myPlugin, { name: "zibo" });
const vm = app.mount('#root');
</script>
</html>
Copy the code
The results
Do more with plug-ins
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<title>hello vue</title>
<! Vue library -->
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="root"></div>
</body>
<script>
// Plugnin plugin: also encapsulates versatility
// Define the plug-in
const myPlugin = {
install(app, options){
// This app is the root component. You can do a lot of things through app
// Add attributes to descendant components
app.provide('name'.'zibo');
// Custom instruction
app.directive('focus', {
mounted(el){ el.focus(); }});// Extend global properties
app.config.globalProperties.$sayHello = "hello zibo!"; }}const app = Vue.createApp({
template: `
`
});
app.component("my-title", {
// Receives attributes from the top-level component
inject: ['name'].mounted(){
console.log(this.$sayHello);
},
// When received, it can be used directly in the template
template: `
hello world!
{{name}}
`
});
// Using the plug-in, arguments can be passed in
app.use(myPlugin, { name: "zibo" });
const vm = app.mount('#root');
</script>
</html>
Copy the code