vue.extend的问题
問題場景
使用Vue.extend時(shí)
<template><div><div id="mount-point"></div></div> </template> <script> import Vue from 'vue' export default {mounted() {const Profile = Vue.extend({data() {return {firstName: 'Yan',lastName: 'Hello',alias: '最后'}},template: '<p>{{firstName}} {{lastName}} 組合 {{alias}}</p>'})new Profile().$mount('#mount-point')}, } </script>運(yùn)行后報(bào)
You are using the runtime-only build of Vue where the template compiler is not available. Either pre-compile the templates into render functions, or use the compiler-included build.
原因是:
項(xiàng)目中使用的構(gòu)建版本是runtimeonly,要讓上面代碼有效應(yīng)該在vue.config.js中配置
runtimeonly與runtimeCompiler
runtimeCompiler:完整版(運(yùn)行時(shí)+編譯器)
編譯器:用來將模板字符串編譯成為 JavaScript 渲染函數(shù)的代碼。
運(yùn)行時(shí):用來創(chuàng)建 Vue 實(shí)例、渲染并處理虛擬 DOM 等的代碼?;旧暇褪浅ゾ幾g器的其它一切。
如果你需要在客戶端編譯模板 (比如傳入一個(gè)字符串給 template 選項(xiàng),或掛載到一個(gè)元素上并以其 DOM 內(nèi)部的 HTML 作為模板),就將需要加上編譯器,即完整版:
// 需要編譯器 import Vue from 'vue' import App from '@/App' new Vue({el: "#app",components: { App },template: "<App />" })是不在打包時(shí)進(jìn)行編譯的,是在客戶端(瀏覽器)運(yùn)行時(shí)進(jìn)行編譯的,所以要使用待編譯器的完整版本
runtimeonly: 只包含運(yùn)行時(shí)
當(dāng)使用 vue-loader 或 vueify 的時(shí)候,*.vue 文件內(nèi)部的模板會(huì)在構(gòu)建時(shí)預(yù)編譯成 JavaScript。你在最終打好的包里實(shí)際上是不需要編譯器的,在瀏覽器中可直接運(yùn)行,所以只用運(yùn)行時(shí)版本即可。
// 不需要編譯器 import Vue from 'vue' import App from '@/App' new Vue({el: "#app",render: h => h(App) })因?yàn)檫\(yùn)行時(shí)版本相比完整版體積要小大約 30%,所以應(yīng)該盡可能使用這個(gè)版本。如果你仍然希望使用完整版,則需要在打包工具里配置一個(gè)別名:
module.exports = {// ...resolve: {alias: {'vue$': 'vue/dist/vue.esm.js' // 用 webpack 1 時(shí)需用 'vue/dist/vue.common.js'}} }對(duì)比
下圖為兩種模式下,npm run dev后,在谷歌控制臺(tái)查看main.js引入的vue文件版本
runtimeonly
runtimeCompiler
因?yàn)樵?Vue.js 2.0 中,最終渲染都是通過 render 函數(shù),如果寫 template 屬性,則需要編譯成 render 函數(shù),那么這個(gè)編譯過程會(huì)發(fā)生在運(yùn)行時(shí),所以需要帶有編譯器的版本。很顯然,這個(gè)編譯過程對(duì)性能會(huì)有一定損耗,所以通常我們更推薦使用 Runtime-Only 的 Vue.js。
組件上做一些新邏輯功能
extend.js
import Vue from 'vue' import Toast from '@/components/Toast' const Toast=Vue.extend(Toast) //......Profile相關(guān)代碼 export {Profile,Toast }使用
<template><div><div id="mount-point"></div></div> </template> <script> import {Profile} from '../extend' export default {mounted() {new Profile().$mount('#mount-point')}, } </script>總結(jié)
以上是生活随笔為你收集整理的vue.extend的问题的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 点差法
- 下一篇: 原生JS实现Ajax和JSONP跨域请求