This article has participated in the call for good writing activities, click to view: back end, big front end double track submission, 20,000 yuan prize pool waiting for you to challenge!
Vue.extend belongs to the global API of Vue, which is seldom used in actual business development, because the procedure of using extend is more complicated than that of Vue.component. But in some standalone component development scenarios, the vue.extend + $mount pair is the one we need to focus on.
1. Application scenarios
In the Vue project, after the root instance is initialized, all pages are basically managed through the Router, and components are also registered locally via import, so component creation is a bit less of a concern than extend. But there are several downsides to this:
- Component templates are predefined. What if I want to dynamically render a component from an interface?
- Everything is rendered under #app and registered components are rendered at their current location. What if I want to implement something like window.alert() that prompts the component to call it as if it were a JS function?
This is where the vue. extend + vm.$mount combination comes in handy.
2. Simple and practical
2.1 Basic Usage
Vue.extend(options) parameters: {ObjectCreate a "subclass" using the base Vue constructor. The parameter is an object containing component options; The data option is a special case, but note that in vue.extend () it must be a function;Copy the code
<div id="mount-point"></div>
// Create a constructor
var Profile = Vue.extend({
template: '<p>{{firstName}} {{lastName}} aka {{alias}}</p>'.data: function () {
return {
firstName: 'Walter'.lastName: 'White'.alias: 'Heisenberg'}}})// Create a Profile instance and mount it to an element.
new Profile().$mount('#mount-point')
// The result is as follows:
<p>Walter White aka Heisenberg</p>
Copy the code
As you can see, extend creates a Vue constructor, not a component instance we would normally write, so new Vue({components: $mount(‘#mount-point’) to mount the specified element.
2.2 The second way
You can pass in an element when creating an instance, and the generated component will be mounted to that element, much like $mount.
// 1. Define a vUE template
let tem ={
template:'{{firstName}} {{lastName}} aka {{alias}}'.data:function(){
return{
firstName:'Walter'.lastName:'White'.alias:'Heisenberg'}}/ / 2. Call
const TemConstructor = Vue.extend(tem)
const intance = new TemConstructor({el:"#app"}) // Generate an instance and mount it on #app
Copy the code