牛骨文教育服务平台(让学习变的简单)
博文笔记

vue入门学习笔记

创建时间:2017-03-02 投稿人: 浏览次数:1264

1、看官方挨批文档,安装相应工具

cnpm install vue //安装vue包

cnpm install --global vue-cli //安装cli编译工具

2、创建一个基于 webpack 模板的新项目

vue init webpack my-project (vue init webpack-simple my-project 初学者建议使用这个初始构建项目,本文所讲例子是基于webpack-simple构建的)$ cd my-project$ cnpm install$ npm run dev (开发环境下运行项目,会在浏览器打开)npm run build (打包编译正式环境下面的文件,会在项目文件夹下面生成index.html,dist文件夹,dist文件夹下面有静态资源和build.js文件。直接拷贝这些文件到你的web服务器,然后在web服务器访问index.html,即可看到开发调试看到的界面)

3、创建组件

在工程目录 /src 下创建 component 文件夹,并在 component 文件夹下创建一个 firstcomponent.vue 并写仿照 App.vue 的格式和前面学到的知识写一个组件。

<template>
  <div id="firstcomponent">
    <h1>I am a title.</h1>
    <a> written by {{ author }} </a>
  </div>
</template>

<script type="text/javascript">
export default {
  data () {
    return {
      author: "刘小强,qq号 940235644"
    }
  }
}
</script>

<style>
</style>
4、在 App.vue 使用组件 ( 因为在 index.html 里面定义了<div id="app"></div>所以就以这个组件作为主入口,你可以自己尝试改写)

第一步,在App.vue引入。在 <script></script> 标签内的第一行写

import firstcomponent from "./component/firstcomponent.vue"

第二步,在App.vue注册。在 <script></script> 标签内的 data 代码块后面加上 components: { firstcomponent }。这里要注意:如果你还有其他组件要使用,必须和firstcomponent一样在App.vue里面引入和注册components: { firstcomponent ,secondcomponent}

export default {
  data () {
    return {
      msg: "Hello Vue!"
    }
  },
  components: { firstcomponent }
}

第三步,使用。

在 <template></template> 内加上<firstcomponent></firstcomponent>

<template>
  <div id="app">
    <img src="./assets/logo.png">
    <h1>{{ msg }}</h1>
    <firstcomponent></firstcomponent>
  </div>
</template>完成后的代码ru
<template>
  <div id="app">
    <img src="./assets/logo.png">
    <h1>{{ msg }}</h1>
    <firstcomponent></firstcomponent>
     <secondcomponent></secondcomponent>
    <ul>
      <li><router-link to="/first">第一页</router-link></li>
      <li><router-link to="/second">第二页</router-link></li>
    </ul>
        <router-view class="view"></router-view>
  </div>
</template>

<script>
import firstcomponent from "./component/firstcomponent.vue";
import secondcomponent from "./component/secondcomponent.vue";
export default {
  name: "app",
  data () {
    return {
      msg: "Welcome to Your Vue.js App"
    }
  },
    components: { firstcomponent,secondcomponent }
}
</script>

<style lang="scss">
#app {
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}

h1, h2 {
  font-weight: normal;
}

ul {
  list-style-type: none;
  padding: 0;
}

li {
  display: inline-block;
  margin: 0 10px;
}

a {
  color: #42b983;
}
</style>
5、使用路由搭建单页应用

cnpm install vue-router --save

在 webpack.config.js 加入别名,因为默认配置是运行时构建(构建方式有两种:独立构建和运行时构建,具体可以参考官方文档说明)

resolve: {
    alias: {vue: "vue/dist/vue.js"}
  }
再按之前的方法写一个组件 secondcomponent.vue

然后修改 main.js,引入并注册 vue-router
import VueRouter from "vue-router";
Vue.use(VueRouter);并且配置路由规则和 app 启动配置项加上 router,修改后的 main.js 如下:
import Vue from "vue"
import App from "./App.vue"
import VueRouter from "vue-router";
import VueResource from "vue-resource";
import secondcomponent from "./component/secondcomponent.vue";
import Element from "element-ui";
import "element-ui/lib/theme-default/index.css";
Vue.use(Element);
//开启debug模式
Vue.config.debug = true;


Vue.use(VueRouter);
Vue.use(VueResource);
// 定义组件, 也可以像教程之前教的方法从别的文件引入
const First = { template: "<div><h2>我是第 1 个子页面</h2></div>" }
// 创建一个路由器实例
// 并且配置路由规则
const router = new VueRouter({
    mode: "history",
    base: __dirname,
    routes: [
        {
            path: "/first",
            component: First
        },
        {
            path: "/second",
            component: secondcomponent
        }
    ]
})


// 现在我们可以启动应用了!
// 路由器会创建一个 App 实例,并且挂载到选择符 #app 匹配的元素上。
const app = new Vue({
        router: router,
        render: h => h(App)
}).$mount("#app")

6、给页面加动态数据

这时候的页面都是静态的(数据在写程序的时候已经固定了不能修改),而每个应用基本上都会请求外部数据以动态改变页面内容。对应有一个库叫 vue-resource 帮我们解决这个问题。

使用命令行安装

cnpm install vue-resource --save

在 main.js 引入并注册 vue-resource :

import VueResource from "vue-resource"
Vue.use(VueResource);

我们在 secondcomponent.vue 上来动态加载数据

添加一个列表:

<ul>
      <li v-for="article in articles">
        {{article.title}}
      </li>
    </ul>

在 data 里面加入数组 articles 并赋值为[]

然后在 data 后面加入加入钩子函数 mounted (详细请参照官方文档关于 vue 生命周期的解析),data 和 mount 中间记得记得加逗号

mounted: function() {
    this.$http.jsonp("https://api.douban.com/v2/movie/top250?count=10", {}, {
        headers: {

        },
        emulateJSON: true
    }).then(function(response) {
      // 这里是处理正确的回调

        this.articles = response.data.subjects
        // this.articles = response.data["subjects"] 也可以

    }, function(response) {
        // 这里是处理错误的回调
        console.log(response)
    });
  }
7、添加样式美化页面命令行安装 ElementU

cnpm install element-ui@next -S

然后在 main.js 引入并注册

import Element from "element-ui"
import "element-ui/lib/theme-default/index.css"
Vue.use(Element)

下面三个加载器必须安装

cnpm install style-loader --save-dev

cnpm install css-loader --save-dev

cnpm install file-loader --save-dev

在 webpack.config.js 中的 loaders 数组加入以下配置, 记得该加逗号的地方加逗号!

{
    test: /\.css$/,
    loader: "style!css"
},
{
    test: /\.(eot|woff|woff2|ttf)([\?]?.*)$/,
    loader: "file"
}
修改完的 webpack.config.js 如下

var path = require("path")
var webpack = require("webpack")
module.exports = {
  entry: "./src/main.js",
  output: {
    path: path.resolve(__dirname, "./dist"),
    publicPath: "/dist/",
    filename: "build.js"
  },
  module: {
    rules: [
      {
        test: /.vue$/,
        loader: "vue-loader",
        options: {
          loaders: {
            // Since sass-loader (weirdly) has SCSS as its default parse mode, we map
            // the "scss" and "sass" values for the lang attribute to the right configs here.
            // other preprocessors should work out of the box, no loader config like this necessary.
            "scss": "vue-style-loader!css-loader!sass-loader",
            "sass": "vue-style-loader!css-loader!sass-loader?indentedSyntax"
          }
          // other vue-loader options go here
        }
      },
      {
        test: /.js$/,
        loader: "babel-loader",
        exclude: /node_modules/
      },
      {
        test: /.(png|jpg|gif|svg)$/,
        loader: "file-loader",
        options: {
          name: "[name].[ext]?[hash]"
        }
      },
 {
        test: /.css$/,
        loader: "style-loader!css-loader"
      },
      {
        test: /.(eot|woff|woff2|ttf)([\?]?.*)$/,
        loader: "file-loader"
       }
    ]
  },
  resolve: {
    alias: {
     // "vue$": "vue/dist/vue.esm.js",
        vue: "vue/dist/vue.js"
    }
  },
  devServer: {
    historyApiFallback: true,
    noInfo: true
  },
  performance: {
    hints: false
  },
  devtool: "#eval-source-map"
}


if (process.env.NODE_ENV === "production") {
  module.exports.devtool = "#source-map"
  // http://vue-loader.vuejs.org/en/workflow/production.html
  module.exports.plugins = (module.exports.plugins || []).concat([
    new webpack.DefinePlugin({
      "process.env": {
        NODE_ENV: ""production""
      }
    }),
    new webpack.optimize.UglifyJsPlugin({
      sourceMap: true,//不生成源码映射
      compress: {
        warnings: false
      }
    }),
    new webpack.LoaderOptionsPlugin({
      minimize: true
    })
  ])
}

给豆瓣的电影列表套个衣服(样式) :

<el-card class="box-card">
      <div slot="header" class="clearfix">
        <h1 style="line-height: 36px; color: #20A0FF">豆瓣电影排行榜</h2>
      </div>
      <div v-for="article in articles" class="text item">
        {{article.title}}
      </div>
</el-card>

编译

npm run build







            
                
				
			
		
        	
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。