vue开发中遇到问题

1、vue内使用vue-cli默认模板build/dev-server.js开发模拟接口数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
模拟接口数据添加在app下面
var app = express()
....
// ------ 自定义API服务 -------
var comicGradeData = require('../mockData/comic_grade.json')
var apiRoutes = express.Router()
apiRoutes.post('/comic_grade', function (req, res) {
res.json({
code: 200,
message: "漫画分级",
data: comicGradeData
})
})
访问地址为: /api/address
app.use('/data', apiRoutes)
// ---- 自定义API服务-end -----

注意:默认貌似webpack加载json会报错,可以使用webpack提供的json-loader加载

使用方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
npm install --save-dev json-loader

webpack.config.js内添加下面配置:

module.exports = {
module: {
loaders: [
{
test: /\.json$/,
loader: 'json-loader'
}
]
}
}

const json = require('./file.json')

import json from "./file.json"都可以

参考:http://www.css88.com/doc/webpack/loaders/json-loader/

2、全局加载第三方库可以使用如下方法

eg. 第三方库moment:

1
2
3
4
5
6
7
import moment from 'moment'

Object.definePrototype(Vue.prototype, '$moment', { value: moment })

或直接添加到Vue的原型上

Vue.prototype.$moment = moment;

ps. Object.define的方式创建的属性是只读的,如果有人重写this.$moment=’….’会提示TypeError: Cannot assign to read only property

也可以使用插件的形式:

1
2
3
// script.js
import MyLibraryPlugin from 'my-library-plugin';
Vue.use(MyLibraryPlugin);

以axios.js为例子,插件必须公开一个 install 方法,并且将 Vue 构造函数作为第一个参数:

1
2
3
4
5
6
7
// axios.js
import axios from 'axios';
export default {
install: function(Vue,) {
Object.defineProperty(Vue.prototype, '$http', { value: axios });
}
}

然后就可以使用vue.use(plugin)的方法添加插件到全局

1
2
3
4
5
6
7
8
// entry.js
import AxiosPlugin from './axios.js';
Vue.use(AxiosPlugin);
new Vue({
created() {
console.log(this.$http ? 'Axios works!' : 'Uh oh..');
}
})

参考自:http://www.css88.com/archives/7939

3、注册全局filter

1
2
3
4
5
6
7
8
import * as filters from '@/common/filters/filter'

// 遍历并注册filter
Object.keys(filters).forEach(
key => {
Vue.filter(key, filters[key])
}
)

4、v-html内使用filter可采用:

1
v-html="$options.filters.upDown(item)"
# vue
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×