跳到主要内容

Vue单文件组件

· 阅读需 3 分钟
Yana Ching
Front End Engineer

Vue 单文件组件的基本用法

单文件组件的组成结构

  • template 组件模板区域
  • script 业务逻辑区域
  • style 样式区域

webpack中配置vue组件的加载器

- 运行 npm i vue-loader vue-template-compiler -D 命令 
- 在 webpack.config.js 配置文件中,添加 vue-loader 的配置项如下:
const VueLoaderPlugin = require('vue-loader/lib/plugin')
module.exports = {
module: {
rules: [ // ... 其它规则
{ test: /\.vue$/, loader: 'vue-loader' }
]
},
plugins: [ // ... 其它插件
new VueLoaderPlugin() // 请确保引入这个插件! ]
}

运行的时候遇到错误

Module not found: Error: Can't resolve 'vue' in 'D:\Z-work space\DOC\reading_IT\webpack-study\src\components'
解决方法
npm i vue

在 webpack 项目中使用 vue

- 运行 npm i vue -S 安装vue
- 在 src -> index.js 入口文件中,通过 import Vue from 'vue' 来导入 vue 构造函数
- 创建 vue 的实例对象,并制订要控制的 el 区域
- 通过 render 函数渲染 App 根组件
// 1. 导入 Vue 构造函数 import Vue from 'vue' 
// 2. 导入 App 根组件 import App from './components/App.vue'

const vm = new Vue({
// 3. 指定 vm 实例要控制的页面区域
el: '#app',
// 4. 通过 render 函数,把指定的组件渲染到 el 区域中
render: h => h(App)
}
// render: function(createElements) {
// var html = createElements(App) // 返回渲染出来的 HTML结构
// return html
// }
// ========== 相当于 =================
// render: createElements => {
// return createElements(App)
// }
// ========== 使用时 =================
// render: h => h(App)

webpack 打包发布

通过package.json文件配置打包

"scripts" {
// 用于打包的命令
"build": "webpack -p",
// 用于开发调试的命令
"dev": "webpack-dev-server --open --host 127.0.0.1 --port 3000"
}

打包报错:

npm ERR! file D:\Z-work space\DOC\reading_IT\webpack-study\package.json npm ERR! code EJSONPARSE npm ERR! JSON.parse Failed to parse json npm ERR! JSON.parse Unexpected token / in JSON at position 223 while parsing near '...entBase src --hot", // 调试开发命令 npm ERR! JSON.parse "dev1"...' npm ERR! JSON.parse Failed to parse package.json data. npm ERR! JSON.parse package.json must be actual JSON, not just JavaScript.

原因:package.json 文件中不能添加 注释 ' // '