Vue系列(三):组件及数据传递、路由、单文件组件、vue-cli脚手架

<h3><a href="https://segmentfault.com/a/1190000012967337"><strong>上一篇:</strong>Vue系列(二):发送Ajax、JSONP请求、Vue生命周期及实例属性和方法、自定义指令与过渡</a></h3> <h2>1、 组件component</h2> <h3>1. 什么是组件?</h3>css

组件(Component)是 Vue.js 最强大的功能之一。组件能够扩展 HTML 元素,封装可重用的代码
组件是自定义元素(对象)

<h3>2. 定义组件的方式</h3>html

方式1:先建立组件构造器,而后由组件构造器建立组件
方式2:直接建立组件
&lt;div id="itany"&gt;
        &lt;hello&gt;&lt;/hello&gt;
        &lt;my-world&gt;&lt;/my-world&gt;
    &lt;/div&gt;

    &lt;script&gt;
        /**
         * 方式1:先建立组件构造器,而后由组件构造器建立组件
         */
        //1.使用Vue.extend()建立一个组件构造器
        var MyComponent=Vue.extend({
            template:'&lt;h3&gt;Hello World&lt;/h3&gt;'
        });
        //2.使用Vue.component(标签名,组件构造器),根据组件构造器来建立组件
        Vue.component('hello',MyComponent);
        
        /**
         * 方式2:直接建立组件(推荐)
         */
        // Vue.component('world',{
        Vue.component('my-world',{
            template:'&lt;h1&gt;你好,世界&lt;/h1&gt;'
        });
        var vm=new Vue({ //这里的vm也是一个组件,称为根组件Root
            el:'#itany',
            data:{
                msg:'网博'
            }
        });    
    &lt;/script&gt;

<p><a href="https://github.com/tcyfree/VueLearn/blob/master/day03/01.html" rel="nofollow noreferrer">定义组件</a></p> <h3>3. 组件的分类</h3>前端

分类:全局组件、局部组件
&lt;div id="itany"&gt;
        &lt;my-hello&gt;&lt;/my-hello&gt;
        &lt;my-world&gt;&lt;/my-world&gt;
    &lt;/div&gt;

    &lt;script&gt;
        /**
         * 全局组件,能够在全部vue实例中使用
         */
        Vue.component('my-hello',{
            template:'&lt;h3&gt;{{name}}&lt;/h3&gt;',
            data:function(){ //在组件中存储数据时,必须以函数形式,函数返回一个对象
                return {
                    name:'alice'
                }
            }
        });
        /**
         * 局部组件,只能在当前vue实例中使用
         */
        var vm=new Vue({
            el:'#itany',
            data:{
                name:'tom'
            },
            components:{ //局部组件
                'my-world':{
                    template:'&lt;h3&gt;{{age}}&lt;/h3&gt;',
                    data(){
                        return {
                            age:25
                        }
                    }
                }
            }
        });    
    &lt;/script&gt;

<p><a href="https://github.com/tcyfree/VueLearn/blob/master/day03/02.html" rel="nofollow noreferrer">组件的分类</a></p> <h3>4. 引用模板</h3>vue

将组件内容放到模板&lt;template&gt;中并引用,必须有且只有一个根元素
&lt;div id="itany"&gt;
        &lt;my-hello&gt;&lt;/my-hello&gt;
        &lt;my-hello&gt;&lt;/my-hello&gt;
    &lt;/div&gt;

    &lt;template id="wbs"&gt;
        &lt;!-- &lt;template&gt;必须有且只有一个根元素 --&gt;
        &lt;div&gt;
            &lt;h3&gt;{{msg}}&lt;/h3&gt;
            &lt;ul&gt;
                &lt;li v-for="value in arr"&gt;{{value}}&lt;/li&gt;
            &lt;/ul&gt;
        &lt;/div&gt;
    &lt;/template&gt;

    &lt;script&gt;
        var vm=new Vue({
            el:'#itany',
            components:{
                'my-hello':{
                    name:'wbs17022',  //指定组件的名称,默认为标签名,能够不设置
                    template:'#wbs',
                    data(){
                        return {
                            msg:'欢迎来到南京网博',
                            arr:['tom','jack','mike']
                        }
                    }
                }
                
            }
        });    
    &lt;/script&gt;

<p><a href="https://github.com/tcyfree/VueLearn/blob/master/day03/03.html" rel="nofollow noreferrer">引用模板</a></p> <h3>5. 动态组件</h3>node

&lt;component :is=""&gt;组件
    多个组件使用同一个挂载点,而后动态的在它们之间切换    

&lt;keep-alive&gt;组件
&lt;div id="itany"&gt;
        &lt;button @click="flag='my-hello'"&gt;显示hello组件&lt;/button&gt;
        &lt;button @click="flag='my-world'"&gt;显示world组件&lt;/button&gt;


        &lt;div&gt;
            &lt;!-- 使用keep-alive组件缓存非活动组件,能够保留状态,避免从新渲染,默认每次都会销毁非活动组件并从新建立 --&gt;
            &lt;keep-alive&gt;
                &lt;component :is="flag"&gt;&lt;/component&gt;    
            &lt;/keep-alive&gt;
        &lt;/div&gt;
    &lt;/div&gt;

    &lt;script&gt;
        var vm=new Vue({
            el:'#itany',
            data:{
                flag:'my-hello'
            },
            components:{
                'my-hello':{
                    template:'&lt;h3&gt;我是hello组件:{{x}}&lt;/h3&gt;',
                    data(){
                        return {
                            x:Math.random()
                        }
                    }
                },
                'my-world':{
                    template:'&lt;h3&gt;我是world组件:{{y}}&lt;/h3&gt;',
                    data(){
                        return {
                            y:Math.random()
                        }
                    }
                }
            }
        });    
    &lt;/script&gt;

<p><a href="https://github.com/tcyfree/VueLearn/blob/master/day03/04.html" rel="nofollow noreferrer">动态组件</a></p> <h2>2、 组件间数据传递</h2> <h3>1. 父子组件</h3> <p>在一个组件内部定义另外一个组件,称为父子组件 <br><strong>子组件只能在父组件内部使用</strong><br><strong>默认状况下,子组件没法访问父组件中的数据,每一个组件实例的做用域是独立的</strong></p> <h3>2. 组件间数据传递 (通讯)</h3> <h4>2.1 子组件访问父组件的数据</h4>webpack

a)在调用子组件时,绑定想要获取的父组件中的数据
b)在子组件内部,使用props选项声明获取的数据,即接收来自父组件的数据
总结:父组件经过props向下传递数据给子组件

<p><strong>注:组件中的数据共有三种形式:</strong><code>data</code>、<code>props</code>、<code>computed</code></p> <h4>2.2 父组件访问子组件的数据</h4>ios

a)在子组件中使用vm.$emit(事件名,数据)触发一个自定义事件,事件名自定义
b)父组件在使用子组件的地方监听子组件触发的事件,并在父组件中定义方法,用来获取数据
总结:子组件经过events给父组件发送消息,实际上就是子组件把本身的数据发送到父组件

<p><a href="https://github.com/tcyfree/VueLearn/blob/master/day03/05.html" rel="nofollow noreferrer">父子组件及组件间数据传递</a></p> <h3>3. 单向数据流</h3>git

props是单向绑定的,当父组件的属性变化时,将传导给子组件,可是不会反过来
并且不容许子组件直接修改父组件中的数据,报错
解决方式:
    方式1:若是子组件想把它做为局部数据来使用,能够将数据存入另外一个变量中再操做,不影响父组件中的数据
    方式2:若是子组件想修改数据而且同步更新到父组件,两个方法:
        a.使用.sync(1.0版本中支持,2.0版本中不支持,2.3版本又开始支持)
            须要显式地触发一个更新事件
        b.能够将父组件中的数据包装成对象,而后在子组件中修改对象的属性(由于对象是引用类型,指向同一个内存空间),推荐

<p><a href="https://github.com/tcyfree/VueLearn/blob/master/day03/06.html" rel="nofollow noreferrer">单向数据流</a></p> <h3>4. 非父子组件间的通讯</h3>github

非父子组件间的通讯,能够经过一个空的Vue实例做为中央事件总线(事件中心),用它来触发事件和监听事件

var Event=new Vue();
Event.$emit(事件名,数据);
Event.$on(事件名,data =&gt; {});

<p><a href="https://github.com/tcyfree/VueLearn/blob/master/day03/07.html" rel="nofollow noreferrer">非父子组件间的通讯</a></p> <h2>3、 slot内容分发</h2>web

本意:位置、槽
做用:用来获取组件中的原内容,相似angular中的transclude指令

<p><a href="https://github.com/tcyfree/VueLearn/blob/master/day03/08.html" rel="nofollow noreferrer">slot内容分发</a></p> <h2>4、 vue-router路由</h2> <h3>1. 简介</h3>

使用Vue.js开发SPA(Single Page Application)单页面应用
根据不一样url地址,显示不一样的内容,但显示在同一个页面中,称为单页面应用

<p><a href="https://router.vuejs.org/zh-cn" rel="nofollow noreferrer">参考</a></p>

bower info vue-router
cnpm install vue-router -S

<h3>2. 基本用法</h3>

a.布局
b.配置路由
&lt;div id="itany"&gt;
        &lt;div&gt;
            &lt;!-- 使用router-link组件来定义导航,to属性指定连接url --&gt;
            &lt;router-link to="/home"&gt;主页&lt;/router-link&gt;
            &lt;router-link to="/news"&gt;新闻&lt;/router-link&gt;
        &lt;/div&gt;
        &lt;div&gt;
            &lt;!-- 路由出口 --&gt;
            &lt;!-- 路由匹配到的组件将渲染在这里 --&gt;
            &lt;!-- router-view用来显示路由内容 --&gt;
            &lt;router-view&gt;&lt;/router-view&gt;
        &lt;/div&gt;
&lt;/div&gt;

&lt;script&gt;
        //1.定义组件
        var Home={
            template:'&lt;h3&gt;我是主页&lt;/h3&gt;'
        }
        var News={
            template:'&lt;h3&gt;我是新闻&lt;/h3&gt;'
        }
        //2.配置路由
        const routes=[
            {path:'/home',component:Home},
            {path:'/news',component:News},
            {path:'*',redirect:'/home'} //重定向
        ]
        //3.建立路由实例
        const router=new VueRouter({
            routes, //简写,至关于routes:routes
            // mode:'history', //更改模式
            linkActiveClass:'active' //更新活动连接的class类名
        });
        //4.建立根实例并将路由挂载到Vue实例上
        new Vue({
            el:'#itany',
            router //注入路由
        });
    &lt;/script&gt;

<p><a href="https://github.com/tcyfree/VueLearn/blob/master/day03/09.html" rel="nofollow noreferrer">路由基本用法</a></p> <h3>3. 路由嵌套和参数传递</h3>

传参的两种形式:
    a.查询字符串:login?name=tom&amp;pwd=123
        {{$route.query}}
    b.rest风格url:regist/alice/456
        {{$route.params}}

<h3>4. 路由实例的方法</h3>

router.push()  添加路由,功能上与&lt;route-link&gt;相同
router.replace() 替换路由,不产生历史记录

<h3>5. 路由结合动画</h3> <p><a href="https://github.com/tcyfree/VueLearn/blob/master/day03/10.html" rel="nofollow noreferrer">路由嵌套和参数传递、动画</a></p> <h2>5、 单文件组件</h2> <h3>1. .vue文件</h3>

.vue文件,称为单文件组件,是Vue.js自定义的一种文件格式,一个.vue文件就是一个单独的组件,在文件内封装了组件相关的代码:html、css、js

.vue文件由三部分组成:&lt;template&gt;、&lt;style&gt;、&lt;script&gt;
    &lt;template&gt;
        html
    &lt;/template&gt;

    &lt;style&gt;
        css
    &lt;/style&gt;

    &lt;script&gt;
        js
    &lt;/script&gt;

<h3>2. vue-loader</h3>

浏览器自己并不认为.vue文件,因此必须对.vue文件进行加载解析,此时须要vue-loader
相似的loader还有许多,如:html-loader、css-loader、style-loader、babel-loader等
须要注意的是vue-loader是基于webpack的

<h3>3. webpack</h3>

webpack是一个前端资源模板化加载器和打包工具,它可以把各类资源都做为模块来使用和处理
实际上,webpack是经过不一样的loader将这些资源加载后打包,而后输出打包后文件 
简单来讲,webpack就是一个模块加载器,全部资源均可以做为模块来加载,最后打包输出

<p><a href="http://webpack.github.io/" rel="nofollow noreferrer">webpack官网</a></p>

webpack版本:v1.x v2.x

webpack有一个核心配置文件:webpack.config.js,必须放在项目根目录下

<h3>4. 示例,步骤:</h3> <h4>4.1 建立项目,目录结构 以下:</h4> <p>webpack-demo</p>

|-index.html
|-main.js   入口文件       
|-App.vue   vue文件
|-package.json  工程文件 //npm init --yes
|-webpack.config.js  webpack配置文件
|-.babelrc   Babel配置文件

<h3>4.2 编写App.vue</h3> <h3>4.3 安装相关模板</h3>

cnpm install vue -S

cnpm install webpack -D
cnpm install webpack-dev-server -D

cnpm install vue-loader -D
cnpm install vue-html-loader -D
cnpm install css-loader -D
cnpm install vue-style-loader -D
cnpm install file-loader -D

cnpm install babel-loader -D
cnpm install babel-core -D
cnpm install babel-preset-env -D  //根据配置的运行环境自动启用须要的babel插件
cnpm install vue-template-compiler -D //预编译模板

合并:cnpm install -D webpack webpack-dev-server vue-loader vue-html-loader css-loader vue-style-loader file-loader babel-loader babel-core babel-preset-env  vue-template-compiler

<h3>4.4 编写main.js</h3>

import Vue from 'vue' //引入内置模块
import App from './App.vue' //引入自定义模块,须要加./

render:function(h){ //使用render函数(推荐)渲染组件,和compnents同样
        return h(App);
    }

/* scoped表示该样式只在当前组件中有效 */

<h3>4.5 编写webpack.config.js</h3> <h3>4.6 编写.babelrc</h3> <h3>4.7 编写package.json</h3> <h3>4.8 运行测试</h3>

npm run dev

<p><a href="https://github.com/tcyfree/VueLearn/tree/master/day03/webpack-demo" rel="nofollow noreferrer">webpack-demo</a></p> <h2>6、 vue-cli脚手架</h2> <h3>1. 简介</h3>

vue-cli是一个vue脚手架,能够快速构造项目结构
vue-cli自己集成了多种项目模板:
    simple  不多简单
    webpack 包含ESLint代码规范检查和unit单元测试等
    webpack-simple 没有代码规范检查和单元测试
    browserify 使用的也比较多
    browserify-simple

<h3>2. 示例,步骤:</h3> <p><a href="https://cn.vuejs.org/v2/guide/installation.html#%E5%91%BD%E4%BB%A4%E8%A1%8C%E5%B7%A5%E5%85%B7-CLI" rel="nofollow noreferrer">官网安装示例</a></p> <h4>2.1 安装vue-cli,配置vue命令环境</h4>

cnpm install vue-cli -g
vue --version
vue list

<h4>2.2 初始化项目,生成项目模板</h4>

语法:vue init 模板名  项目名

<h4>2.3 进入生成的项目目录,安装模块包</h4>

cd vue-cli-demo
cnpm install

<h4>2.4 运行</h4>

npm run dev  //启动测试服务
npm run build //将项目打包输出dist目录,项目上线的话要将dist目录拷贝到服务器上

<h3>3. 使用webpack模板</h3>

vue init webpack vue-cli-demo2

ESLint是用来统一代码规范和风格的工具,如缩进、空格、符号等,要求比较严格

<p><a href="http://eslint.org" rel="nofollow noreferrer">官网</a></p>

问题Bug:若是版本升级到node 8.0 和 npm 5.0,控制台会报错:
    GET http://localhost:8080/__webpack_hmr net::ERR_INCOMPLETE_CHUNKED_ENCODING
解决方法:
    a)下降Node版本到7.9或如下
    b)修改build/dev-server.js文件,以下:
        var hotMiddleware = require('webpack-hot-middleware')(compiler, {
          log: () =&gt; {},
          heartbeat:2000 //添加此行
        })
    参考:https://github.com/vuejs-templates/webpack/issues/731

<h3><a href="https://segmentfault.com/a/1190000013036608"><strong>下一篇:</strong>Vue系列(四):模块化开发、Elment UI、自定义全局组件(插件)、Vuex</a></h3> <p>参考Vue教学视频:<a href="http://edu.51cto.com/course/10543.html" rel="nofollow noreferrer">Vue.js 2.0之全家桶系列视频课程(vue、vue-router、axios、vuex)</a></p>

原文地址:http://www.javashuo.com/article/p-tnzbortr-cp.html

相关文章
相关标签/搜索