前端框架VUE的基礎使用

一、概述

Vue 是一套用於構建用戶界面的漸進式框架。與其它大型框架不一樣的是,Vue 被設計爲能夠自底向上逐層應用。Vue 的核心庫只關注視圖層,不只易於上手,還便於與第三方庫或既有項目整合。另外一方面,當與現代化的工具鏈以及各類支持類庫結合使用時,Vue 也徹底可以爲複雜的單頁應用提供驅動。css

二、基礎使用

一、安裝node.js

nodejs.cn/downloadhtml

二、安裝vue-cli 快速生成項目模板

cmd > npm install vue-cli -gvue

三、建立基於webpack模板的vue應用

vue init webpack vue-spring-cloud node

四、基本語法demo

test.vuewebpack

<template>
  <div>
    <span>測試取值:{{message}}</span>
    <div>測試v-if:
      <span v-if="flag1">true</span>
      <span v-if="flag2==false">false</span>
    </div>
    <div>測試v-for:
      <span v-for="arr in array" >
       {{arr}}、
     </span>
    </div>
    <div>測試v-on:
      <button v-on:click="testEvent()">點我點我</button>
    </div>
    <HelloWorld></HelloWorld>

    <div>雙向綁定測試:<input v-model="name" /><button v-on:click="alertName()">點擊彈出值</button></div>


    <div>組件消息傳遞測試
      <Children  v-bind:message='{name:"消息傳遞"}' v-on:send="setChidrenData"></Children>
      <span>子組件傳來的消息:{{chidrenData}}</span>
    </div>
  </div>
</template>

<script>
  import HelloWorld from "../components/HelloWorld";
  import Children from "../components/Children";
  // 先註冊組件

  export default {
    name: "test",
    components: {Children, HelloWorld},
    data() {
      return {
        name:"雙向綁定測試",
        message: '測試取值',
        //測試v-if
        flag1 : true,
        flag2 : false,
        //測試v-for
        array: ['1','2','3'],
        chidrenData:''
      }
    },
    methods:{
      //測試事件綁定
      testEvent(){
        alert('點我點我');
      },
      //雙向綁定測試
      alertName(){
        alert(this.name);
      },
      //子組件傳遞須要經過父組件事件
      setChidrenData(msg){
        this.chidrenData = msg
      }
    },
    //鉤子函數測試
    beforeCreate:function () {
      alert('鉤子函數測試');
    },


  }
</script>

<style lang="scss" scoped>
  .login-box {
    border: 1px solid #DCDFE6;
    width: 350px;
    margin: 180px auto;
    padding: 35px 35px 15px 35px;
    border-radius: 5px;
    -webkit-border-radius: 5px;
    -moz-border-radius: 5px;
    box-shadow: 0 0 25px #909399;
  }

  .login-title {
    text-align: center;
    margin: 0 auto 40px auto;
    color: #303133;
  }
  .login-input{
    width: 220px;
  }
</style>

複製代碼

Children.vueios

<template>
  <div>
    <div>父組件傳來的消息:{{message}}</div>
    <div>傳遞消息給父組件:
      <input v-model="data"><button v-on:click="sendMessage()">發送</button>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Children',
  props:['message'],
  data(){
    return{
      data:''
    }
  },
  methods:{
    sendMessage(){
      this.$emit('send',this.data);
    }
  }
}
</script>


複製代碼

HelloWorld.vueweb

<template>
  <div>
    <div>自定義組件測試</div>
    <div>父組件傳來的消息:{{data}}</div>
  </div>

</template>

<script>
export default {
  name: 'HelloWorld',
  props:['data']
}
</script>

複製代碼

三、登陸頁實現以及測試demo

一、安裝依賴

切換項目下執行命令spring

一、安裝elementUi vue佈局框架

element-ui官網vue-router

cmd > npm i element-ui -Svue-cli

二、安裝vue-router 路由

cmd > npm install vue-router --save-dev

三、 安裝 SASS 加載器css

cmd > npm install sass-loader node-sass --save-dev

四、初始化工程

cmd > npm install

若出現 Unexpected end of JSON input while parsing near

cmd > npm cache clean --force 後從新 npm install

五、命令說明

  • --save :安裝到項目文件下並在dependencies引入模塊

  • --save-dev :安裝到項目文件下並在devDependencies引入模塊

  • -g :全局安裝

六、運行項目

cmd > npm run dev

二、基於element-ui 的vue簡單登陸註冊頁

一、建立路由

import Vue from 'vue'
import Router from 'vue-router'
import Login from '../views/Login'
import Register from '../views/Register'
import Main from '../views/Main'
import Test from '../views/test'

Vue.use(Router);

export default new Router({
  routes: [{
    // 登陸頁
    path: '/login',
    name: 'Login',
    // 模塊名
    component: Login
  },
    //註冊頁
    {
      path: '/register',
      name: 'Register',
      component: Register
    }]
});

複製代碼

二、修改main.js

import Vue from 'vue'
//導入 vue-router
import VueRouter from 'vue-router'
import router from './router'

// 導入 ElementUI
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'

import App from './App'

// 安裝路由
Vue.use(VueRouter);

// 安裝 ElementUI
Vue.use(ElementUI);

new Vue({
  el: '#app',
  // 啓用路由
  router,
  // 啓用 ElementUI
  render: h => h(App)
});
複製代碼

三、建立登陸頁

<template>
  <div>
    <!--:model 綁定表單對象 :rules 綁定表單驗證-->
    <el-form ref="form" :model="form" :rules="rules"  label-width="80px" class="login-box">
      <h3 class="login-title">vue-spring-cloud</h3>
      <!--prop 綁定驗證字段-->
      <el-form-item label="帳號:"  prop="username">
        <el-input type="text" placeholder="請輸入帳號" v-model="form.username" class="login-input"></el-input>
      </el-form-item>
      <el-form-item label="密碼:"  prop="password">
        <el-input type="password" placeholder="請輸入密碼" v-model="form.password" class="login-input"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary"  v-on:click="onSubmit('form')" >登陸</el-button>
        <el-button type="primary"  v-on:click="register()" >註冊</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  export default {
    name: "login",
    data() {
      return {
        form: {
          username: '',
          password: ''
        },
        rules: {
          username: [
            { required: true, message: '請輸入用戶名', trigger: 'blur' },
          ],
          password: [
            { required: true, message: '請輸入密碼', trigger: 'blur' },
          ]
        }
      }
    },
    methods: {
      //自定義事件
      onSubmit(formName){
        //表單驗證(valid=驗證返回值)
        this.$refs[formName].validate((valid) => {
          if (valid) {
            //路由到主頁
            this.$router.push('/main');
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      //自定義事件
      register(){
        //路由到註冊頁
        this.$router.push('/register');
      }
    }
  }
</script>

<style lang="scss" scoped>
  .login-box {
    border: 1px solid #DCDFE6;
    width: 350px;
    margin: 180px auto;
    padding: 35px 35px 15px 35px;
    border-radius: 5px;
    -webkit-border-radius: 5px;
    -moz-border-radius: 5px;
    box-shadow: 0 0 25px #909399;
  }

  .login-title {
    text-align: center;
    margin: 0 auto 40px auto;
    color: #303133;
  }
  .login-input{
    width: 220px;
  }
</style>

複製代碼

四、建立註冊頁

<template>
  <div>
    <!--:model 綁定表單對象 :rules 綁定表單驗證-->
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="form-box">
      <h3 class="form-title">vue-spring-cloud</h3>
      <!--prop 綁定驗證字段-->
      <el-form-item label="用戶名稱" prop="userName">
        <!--: v-model 數據雙向綁定-->
        <el-input  placeholder="請輸入用戶名"  v-model="ruleForm.userName"></el-input>
      </el-form-item>
      <el-form-item label="用戶密碼" prop="password">
        <el-input type="password"  placeholder="請輸入密碼" v-model="ruleForm.password"></el-input>
      </el-form-item>
      <el-form-item label="確認密碼" prop="isPassword">
        <el-input type="password" placeholder="請確認密碼" v-model="ruleForm.isPassword"></el-input>
      </el-form-item>
      <el-form-item>
        <!---事件綁定--->
        <el-button type="primary" @click="submitForm('ruleForm')">註冊</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  export default {
    name: "Register",
    data() {
      //自定義驗證名(rule=觸發元素 value=文本值 callback=回調驗證)
      var checkPass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('請輸入密碼'));
        } else {
          if (this.ruleForm.password !== '') {
            this.$refs.ruleForm.validateField('isPassword');
          }
          callback();
        }
      };
      var checkPass2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('請再次輸入密碼'));
        } else if (value !== this.ruleForm.password) {
          callback(new Error('兩次輸入密碼不一致!'));
        } else {
          callback();
        }
      };

      return {
        ruleForm: {
          userName: '',
          password: '',
          isPassword:''
        },
        //表單驗證
        rules: {
          userName: [
            { required: true, message: '請輸入用戶名', trigger: 'blur' },
          ],
          password: [
            { required: true, message: '請輸入密碼', trigger: 'blur' },
            { validator: checkPass, trigger: 'blur' }
          ],
          isPassword: [
            { required: true, message: '請確認密碼', trigger: 'blur' },
            { validator: checkPass2, trigger: 'blur' }
          ]
        }
      };
    },
    methods: {
      //自定義事件
      submitForm(formName) {
        //表單驗證(valid=驗證返回值)
        this.$refs[formName].validate((valid) => {
          if (valid) {
            //vue-router 調整登陸頁
            this.$router.push('/login')
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      //重置表單內容
      resetForm(formName) {
        this.$refs[formName].resetFields();
      }
    },
  }
</script>

<style lang="scss" scoped>
  .form-box {
    border: 1px solid #DCDFE6;
    width: 350px;
    margin: 180px auto;
    padding: 35px 35px 15px 35px;
    border-radius: 5px;
    -webkit-border-radius: 5px;
    -moz-border-radius: 5px;
    box-shadow: 0 0 25px #909399;
  }
  .form-title{
    text-align: center;
  }

</style>


<style scoped>

</style>

複製代碼

五、修改App.vue

<template>
  <div id="app">
    <!--路由組件-->
    <router-view/>
  </div>
</template>

<script>
  export default {
    name: 'App'
  }
</script>

複製代碼

六、頁面效果

三、嵌套路由與參數傳遞

一、route index.js

//主頁
    {
      path: '/main/:username',
      name: 'Main',
      component: Main,
      //支持props方法傳參
      props:true,

      //嵌套路由
      children: [
        {
          //:/id傳遞參數名
          path: '/param/param1/:id',
          name: 'param1',
          component: param1,
        }, {
          path: '/param/param2/:id',
          name: 'param2',
          component: param2,
        }, {
          path: '/param/param3/:id',
          name: 'param3',
          component: param3,
          props:true
        }
      ]
    },
複製代碼

二、Main.vue

<template>
<div>
  <el-container>
    <el-aside width="200px">
      <el-menu :default-openeds="['1']">
        <el-submenu index="1">
          <template slot="title"><i class="el-icon-caret-right"></i>傳參測試</template>
          <el-menu-item-group>
            <el-menu-item index="1-1">
                <!--props方式獲取登錄頁傳值-->
                 當前登陸人:{{username}}
            </el-menu-item>
            <el-menu-item index="1-1">
              <!--路由跳轉-->
              <router-link to="/param/param1/傳參測試1">傳參測試1</router-link>
            </el-menu-item>
            <el-menu-item index="1-2">
              <!--路由跳轉 :to 對象模式傳遞 name:路由名稱 params:路由參數-->
              <router-link :to="{name:'param2',params:{id:'傳參測試2'}}">傳參測試2</router-link>
            </el-menu-item>
            <el-menu-item index="1-3">
              <router-link :to="{name:'param3',params:{id:'傳參測試3'}}">傳參測試3</router-link>
            </el-menu-item>
          </el-menu-item-group>
        </el-submenu>
      </el-menu>
    </el-aside>

    <el-container>
      <el-main>
        <router-view />
      </el-main>
    </el-container>
  </el-container>
</div>
</template>

<script>
export default {
  //props 方式傳值
  props: ['username'],
  name: "Main"
}
</script>

<style scoped lang="scss">
.el-header {
  background-color: #B3C0D1;
  color: #333;
  line-height: 60px;
}

.el-aside {
  color: #333;
}
</style>


複製代碼

三、參數取值頁面

param1

<template>
<div>傳參測試1:{{$route.params.id}}</div>
</template>

<script>
export default {
  name: "param1"
}
</script>

<style scoped>

</style>
複製代碼

param2

<template>
  <div>傳參測試2:{{$route.params.id}}</div>
</template>

<script>
  export default {
    name: "param2"
  }
</script>

<style scoped>

</style>
複製代碼

param3 props取值

<template>
  <div>傳參測試3:{{id}}</div>
</template>

<script>
  export default {
    props: ['id'],
    name: "param3"
  }
</script>

<style scoped>

</style>
複製代碼

四、效果

四、重定向

一、路由配置

//重定向回到登陸
    {
      path: '/toLogin',
      redirect: '/login',
      name:'redirect',
    },
複製代碼

二、router-link

<router-link :to="{name:'redirect'}">退出登陸</router-link>
複製代碼

五、路由鉤子

beforeRouteEnter: (to, from, next) => {
      console.log("參數測試頁面進入前");
      next();
    },
    beforeRouteLeave: (to, from, next) => {
      console.log("參數測試頁面跳轉前");
      next();
    }
複製代碼
  • to:路由將要跳轉的路徑信息
  • from:路徑跳轉前的路徑信息
  • next:路由的控制參數
  • next() 跳入下一個頁面
  • next('/path') 改變路由的跳轉方向,使其跳到另外一個路由
  • next(false) 返回原來的頁面
  • next((vm)=>{}) 僅在 beforeRouteEnter 中可用,vm 是組件實例

六、異步請求axios

一、安裝axios

cmd > npm install axios -S

二、導入axios

// 導入axios
import axios from 'axios'
Vue.prototype.axios = axios;
複製代碼

三、建立param4

<template>
  <div>路由測試</div>
</template>
<script>
    export default {
        name: "param4",
      //路由進入前
      beforeRouteEnter: (to, from, next) => {
        console.log("進入前");
        next(vm => {
          // vm.getDate();
          // vm.postDate();
          vm.getDate();
        });
      },
      //路由跳轉後
      beforeRouteLeave: (to, from, next) => {
        console.log("跳轉前");
        next();
      },
      methods:{
        //後臺直接接收 傳遞類型 query string parameters
        getDate:function(){
          this.axios.get("http://localhost:8089/findUser1",{params:{id:'123'}}).then(function (repos) {
            console.log(repos.data);
          }).catch(function(error){

          })

        },
        //後臺@RequestBody 接收 傳遞類型request payload
        postDate:function(){
          this.axios.post("http://localhost:8089/findUser",{id:'123'}).then(function (repos) {

          }).catch(function(error){

          })

        },
        //後臺直接接收傳遞類型 form date
        postDate1:function(){
          let param = new URLSearchParams();
          param.append("id", "zhonghangAlex");

          this.axios.post("http://localhost:8089/findUser1",param).then(function (repos) {

          }).catch(function(error){

          })

        }
      }
    }
</script>

<style scoped>

</style>


複製代碼

四、配置route

import param4 from '../views/param/param4'
複製代碼
{
          path: '/param/param4',
          name: 'param4',
          component: param4
        }
複製代碼
<router-link :to="{name:'param4'}">路由測試</router-link>
複製代碼

五、測試

進入點擊路由測試後---> beforeRouteEnter --->打印進入前--->路由請求打印數據--->跳轉到路由測試頁

一些基於vue的ui庫 或 框架

後端框架 vue-element-admin

更多VUE ui庫 或 框架

相關文章
相關標籤/搜索