按官网(https://cn.vuejs.org/v2/guide...)一步步来,先安装vue脚手架:html
npm install -g vue-cli
命令行敲vue查看是否安装成功vue
vue init webpack-simple demo
接下来是一些初始化的设置,能够选默认enter下去webpack
cd demo npm install npm run dev
接下来你会看到这么个页面:git
工程目录以下:github
打开项目工程,template 写 html,script写 js,style写样式web
如上工程目录,title-bar.vue是共用的顶部栏,咱们在views文件里的list.vue中引用:vue-router
<template> <div class="list"> <title-bar></title-bar> </div> </template> <script> export default { components: { 'title-bar': require('./../components/title-bar.vue') } } </script>
1. 父组件向子组件通讯vue-cli
在list.vue中的代码以下:npm
<title-bar :titleBar="msg"></title-bar> <script> export default { data(){ return { msg: '这个父组件向子组件传的消息' } } } </script>
在title-bar.vue子组件中用props接收消息json
props: ['titleBar']
2. 子组件向父组件通讯
在子组件的js里的代码是这样的:
this.$emit('fromChildMsg', '这是子组件传递的消息');
在父组件接收的代码以下:
<title-bar @fromChildMsg="listenChildMsg"></title-bar> <script> export default { methods: { listenChildMsg(msg){ console.log(msg); } } } </script>
npm install vue-router --save
而后在main.js里加以下代码:
import VueRouter from 'vue-router' import router from './router' Vue.use(VueRouter); const app = new Vue({ router: new VueRouter(router), render: h => h(App) }).$mount('#app')
在main.js同级目录下建立个router.js,在这在加入路由配置信息:
export default { mode: 'history', base: __dirname, routes: [ { path: '/', redirect: '/home' //重定向 }, { path: '/home', component: require('./views/home.vue') }, { path: '/list', component: require('./views/list.vue') }, { path: '/details/:id', //动态配置 name: 'details', component: require('./views/details.vue') } ] }
App.vue修改为这样:
<template> <div id="app"> <router-view></router-view> </div> </template>
连接是这样写的
<router-link to="/list">click to enter list page</router-link>
npm install vue-resource --save
在main.js中引用并注册
import VueResource from 'vue-resource' Vue.use(VueResource);
在list.vue html中加入列表:
<ul> <li v-for="article in articles"> {{article.title}} </li> </ul>
在 data 里面加入数组 articles 并赋值为[],而后在 data 后面加入加入钩子函数 mounted
mounted(){ this.$http.jsonp('https://api.douban.com/v2/movie/in_theaters?count=20').then(res => { this.articles= res.data.subjects; }); }
ps:
https://api.douban.com/v2/mov... 这是豆瓣公开的正在热映电影接口
下面是github的源码分享:
https://github.com/chenhaiwei...
demo效果如图
欢迎拍砖!!!