編程式的導航,vue頁面布局,marked包的使用


 

昨日內容回顧

1. 組件間的傳值
    1. bus  --> 空Vue對象
        通過向bus對象拋出自定義事件的方式在組件間傳遞信息
    2. 注意事項:
        1. bus.$on()應該在組件mounted(掛載在頁面上)的時候就執行
        2. this對象
2. Vue實例的生命周期鈎子函數(8個)
    1. beforeCreate
        data屬性光聲明沒有賦值的時候
    2. created
        data屬性完成了賦值
    3. beforeMount
        頁面上的{{name}}還沒有被渲染成真正的數據
    4. mounted
        頁面上的{{name}}被渲染成真正的數據
        
    5. beforeUpdate
        數據(data屬性)更新之前會執行的函數
    6. updated
        數據(data屬性)更新完會執行的函數
    7. beforeDestroy
        實例被銷毀之前會執行的函數
    8. destroyed
        實例被銷毀后會執行的函數
3. VueRouter
    在前端做路由的
    1. 基本使用
        1. 先寫路由
        2. 生成路由實例
        3. 將路由實例掛載到Vue對象上
        
        4. <router-link></router-link>
           <router-view></router-view>    <==> <router-view/>
    2. 路由的模糊匹配
        1. path: '/user/:name'     ---> $route.params.name
        2. /user/alex?age=9000     ---> $route.query.age
    
    3. 子路由
        children
    4. 編程式導航
        用JS代碼去控制頁面跳轉
        this.$router.push(...)
4. Vue-CLI
    一個腳手架工具,幫助我們快速的搭建Vue項目
    1. 查看本機安裝的vueCLI的版本
        vue -V    ---> 2.9.6
    2. 使用Vue CLI創建Vue項目
        vue init webpack mysite
    
5. 組件中捕獲原生事件
    .native修飾符
View Code

一、編程式的導航

除了使用 <router-link> 創建 a 標簽來定義導航鏈接,我們還可以借助 router 的實例方法,通過編寫代碼來實現。

router.push(location, onComplete?, onAbort?)

注意:在 Vue 實例內部,你可以通過 $router 訪問路由實例。因此你可以調用 this.$router.push

想要導航到不同的 URL,則使用 router.push 方法。這個方法會向 history 棧添加一個新的記錄,所以,當用戶點擊瀏覽器后退按鈕時,則回到之前的 URL。

當你點擊 <router-link> 時,這個方法會在內部調用,所以說,點擊 <router-link :to="..."> 等同於調用 router.push(...)

聲明式 編程式
<router-link :to="..."> router.push(...)

該方法的參數可以是一個字符串路徑,或者一個描述地址的對象。例如:

// 字符串
router.push('home')

// 對象
router.push({ path: 'home' })

// 命名的路由
router.push({ name: 'user', params: { userId: 123 }})

// 帶查詢參數,變成 /register?plan=private
router.push({ path: 'register', query: { plan: 'private' }})
View Code

注意:如果提供了 pathparams 會被忽略,上述例子中的 query 並不屬於這種情況。取而代之的是下面例子的做法,你需要提供路由的 name 或手寫完整的帶有參數的 path

const userId = 123
router.push({ name: 'user', params: { userId }}) // -> /user/123
router.push({ path: `/user/${userId}` }) // -> /user/123
// 這里的 params 不生效
router.push({ path: '/user', params: { userId }}) // -> /user
View Code

同樣的規則也適用於 router-link 組件的 to 屬性。

在 2.2.0+,可選的在 router.push 或 router.replace 中提供 onComplete 和 onAbort 回調作為第二個和第三個參數。這些回調將會在導航成功完成 (在所有的異步鈎子被解析之后) 或終止 (導航到相同的路由、或在當前導航完成之前導航到另一個不同的路由) 的時候進行相應的調用。

**注意:**如果目的地和當前路由相同,只有參數發生了改變 (比如從一個用戶資料到另一個 /users/1 -> /users/2),你需要使用 beforeRouteUpdate 來響應這個變化 (比如抓取用戶信息)。

router.replace(location, onComplete?, onAbort?)

跟 router.push 很像,唯一的不同就是,它不會向 history 添加新記錄,而是跟它的方法名一樣 —— 替換掉當前的 history 記錄。

聲明式 編程式
<router-link :to="..." replace> router.replace(...)

 

舉例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .active{
            color:red;
        }
    </style>
</head>
<body>
<div id="app">
    <!--編程時導航-->
    <button @click="goHome">去首頁</button>
    <button @click="goList">去列表</button>
    <router-view></router-view>
</div>
</body>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<script>
    let home={
        template:'<div>home</div>'
    };
    let list={
        template:'<div>list</div>'
    }
    const routes=[
        {path:'/home',component:home},
        {path:'/list',component:list}
    ]

    let router=new VueRouter({
        routes:routes,
        linkActiveClass:'active'
    });
    //默認加載第一個路徑
    router.push("/home");
    let vm=new Vue({
        el:"#app",
        methods:{
            //編程式導航
            goHome(){
                //頁面跳轉,push是增加到歷史管理
                this.$router.history.push('/home')
                //go表示前進后退
                //this.$router.history.go(-1)
            },
            goList(){
                this.$router.history.push('/list')
                //將當前歷史管理替換成list
                //this.$router.history.replace('/list')
            }
        },
        // 會在實例中提供兩個屬性this.$route(屬性),this.$router(方法);
        router:router,


    })
</script>
</html>
View Code

訪問網頁,效果如下:

 

二、vue頁面布局

我們要完成這個效果

使用以下命令,創建一個vue項目,具體執行過程,請參考上一篇文章

$ npm install -g vue-cli
$ vue init webpack my-project
$ cd my-project
$ npm install bootstrap@3.3.7 -D
$ npm run dev

去除默認頁面

進入目錄my-project\src\router

查看index.js,在routes里面有一行,它表示組件HelloWorld

component: HelloWorld

查看上面的一行

import HelloWorld from '@/components/HelloWorld'

@表示src目錄

@/components/HelloWorld 表示src\components\HelloWorld.vue

.vue后綴,可以不用寫。

組件統一在目錄中components

 

進入目錄my-project\src\components,查看HelloWorld.vue

在<template></template> 之間的代碼,就是默認首頁,圖片下面的一堆a標簽。

修改<template></template> 之間的代碼。HelloWorld.vue部分代碼如下:

<template>
  <div class="hello">
      <h1>這是首頁!!!</h1>
  </div>
</template>
View Code

 

返回上一級,打開App.vue文件,查看<template></template> 之間的代碼

下面一行,表示一個圖片。assets目錄,可以放一些資源,比如圖片之類的

<img src="./assets/logo.png">

再看下面一行

<router-view/>

它的完整代碼是<router-view><router-view/>。<router-view/>是一個簡寫,它會自動閉合!

初學者,建議使用完整寫法!

 

刪除這2行代碼,增加一個bootstrap的導航條

修改App.vue里面<template></template> 之間的代碼,增加一個nav標簽
修改App.vue里面<script></script> 之間的代碼,導入bootstrap

修改App.vue里面<style><style> 之間的代碼,去掉所有樣式

App.vue完整代碼如下:

<template>
  <div id="app">
    <!--導航條-->
    <nav class="navbar navbar-default">
      <div class="container-fluid">
        <!-- Brand and toggle get grouped for better mobile display -->
        <div class="navbar-header">
          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
                  data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <a class="navbar-brand" href="#">Brand</a>
        </div>

        <!-- Collect the nav links, forms, and other content for toggling -->
        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
          <ul class="nav navbar-nav">
            <li class="active"><a href="#">我的首頁</a></li>
            <li><a href="#">我的筆記</a></li>
          </ul>

          <ul class="nav navbar-nav navbar-right">
            <li><a href="#">登錄</a></li>
            <li class="dropdown">
            <li><a href="#">注冊</a></li>
          </ul>
        </div><!-- /.navbar-collapse -->
      </div><!-- /.container-fluid -->
    </nav>
  </div>
</template>

<script>
  //導入bootstrap
  import 'bootstrap/dist/css/bootstrap.min.css'
export default {
  name: 'App'
}
</script>

<style>

</style>
View Code

訪問網頁,效果如下:

 

增加我的筆記

首先增加路由,路由統一在router目錄

進入目錄my-project\src\router,修改index.js,增加路由/note

為了方便路由擴展,定義常量routeArray,它是一個路由數組

修改默認的導入路由方式

頭部使用import導入Note.vue

index.js完整代碼如下:

import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import Note from '@/components/Note.vue'  //導入我的筆記組件
Vue.use(Router)

// 生成路由數組
var routeArray = [
  {
    path: '/',
    name: '我的首頁',
    component: HelloWorld
  },
  {
    path: '/note',
    name: '我的筆記',
    component: Note
  }
]

// 生成路由實例
var routerObj = new Router({
  mode: 'history',
  routes: routeArray
})

//導入默認路由實例
export default routerObj
View Code

注意:component:Note 這里面的Note,對應就是Note.vue文件

 

進入目錄my-project\src\components,新建文件Note.vue

<template>
  <div>
    <h1>這是我的筆記頁面!</h1>
  </div>
</template>

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

<style>

</style>
View Code

進入目錄my-project\src,查看文件main.js,它是app 入口文件

查看這一行

router, 這個是簡寫,實際的完整代碼是 router:router

因為鍵和值,都是router,所以可以簡寫為router

它實際對應的就是my-project\src\router目錄,這個目錄下有一個index.js,它會自動去加載它!

 

頁面切換效果

在App.vue中的<template></template> 之間的代碼,是網頁導航部分。這里面的我的首頁和我的筆記的a標簽的herf屬性是#,需要修改一下

由於我們使用的是Vue Router,它將組件 (components) 映射到路由 (routes),然后告訴 Vue Router 在哪里渲染它們。

所以a標簽,必須替換為router-link。必須指定,App.vue完整代碼如下:

<template>
  <div id="app">
    <!--導航條-->
    <nav class="navbar navbar-default">
      <div class="container-fluid">
        <!-- Brand and toggle get grouped for better mobile display -->
        <div class="navbar-header">
          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
                  data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <a class="navbar-brand" href="#">Brand</a>
        </div>

        <!-- Collect the nav links, forms, and other content for toggling -->
        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
          <ul class="nav navbar-nav">
            <li class="active">
              <router-link to="/">我的首頁</router-link>
            </li>
            <li>
              <router-link to="/note">我的筆記</router-link>
            </li>
          </ul>

          <ul class="nav navbar-nav navbar-right">
            <li><a href="#">登錄</a></li>
            <li class="dropdown">
            <li><a href="#">注冊</a></li>
          </ul>
        </div><!-- /.navbar-collapse -->
      </div><!-- /.container-fluid -->
    </nav>
    <!--路由出口-->
    <router-view></router-view>
  </div>
</template>

<script>
  //導入bootstrap
  import 'bootstrap/dist/css/bootstrap.min.css'
  export default {
    name: 'App'
  }
</script>

<style>

</style>
View Code

注意:要指定路由出口,否則頁面無法渲染!

 

那么Vue Router如何渲染網頁導航的呢?

main.js,它是app入口文件,在Vue對象中,指定router就是src/router目錄,默認會加載里面的index.js

index.js里面定義了2個path,/和/note,分別對應組件HelloWorld.vue和Note.vue

這2個組件,定義了<template></template>標簽,標簽之間的代碼,就是頁面渲染的部分

 

訪問頁面,效果如下:

為什么首頁的url,后面沒有內容呢?而我的筆記,url后面有一個note

因為首頁的path,就是 / ,它和直接IP+端口訪問,效果是一樣的!

查看src\router\index.js文件

// 生成路由實例
var routerObj = new Router({
  mode: 'history',
  routes: routeArray
})

從我們學習vue的前5天,生成路由實例時,從未指定mode參數。它默認為hash,訪問頁面會發現,url后面,會帶一個#號,發覺沒有?

指定mode為history,就不會有#號了

 

vue項目流程

到這里,先來梳理一下,Vue項目的流程。在開發過程中,一般我們只修改src目錄下的文件。

路由流程如下:

 

解釋:

1. main.js是app入口文件,它里面定義的router,實際就是router目錄

2. router目錄下有一個index.js文件,它會默認加載。就好像使用Apache或者Nginx,指定默認首頁為index.html一樣

3. index.js定義了路由數組,指定一些組件。組件統一存放在components目錄,后綴為.vue的文件,就是一個組件!

 

再來看一下

頁面渲染流程:

解釋:

1. 在main.js中,定義了組件為{ App },它實際對應的就是App.vue

2. 在App.vue中,定義了<template></template>標簽,它是存放html代碼的。

一般使用vue,會先綁定一個<div id="app">,這個是約定俗成的!通俗的來講,就是划分了一塊田。

那么之后的所有操作,都是基於這個div來操作的!

必須指定路由出口,也就是<router-view></router-view>,(</router-view>是簡寫),它才能被瀏覽器渲染!

3. HelloWorld.vue是默認就有的組件,它里面也定義了<template></template>,但是並沒有</router-view>標簽(路由出口)

為什么呢?因為在組件App.vue,它里面已經定義了路由出口,我們所有的操作都是基於這個div來操作的!

不信?有圖有真相!

使用瀏覽器工具,查看html代碼

 

看到一條藍線沒有,它表示一對標簽。看到h1標簽沒有?它是HelloWorld.vue組件才有的標簽!

h1標簽是在<div id="app"></div>里面的!

說到這里,我想大家應該明白了使用webpack模板創建vue項目的整個流程了吧!

 

 for循環導航菜單

查看index.js,routeArray變量是一個數組。它對應的是App.vue中的2個a標簽,這2個a標簽寫死了,我們可以改成for循環,來遍歷數組。方便以后的擴展!

那么如何獲取當前所有路由呢?

修改App.vue,增加一個計算屬性

<template>
  <div id="app">
    <!--導航條-->
    <nav class="navbar navbar-default">
      <div class="container-fluid">
        <!-- Brand and toggle get grouped for better mobile display -->
        <div class="navbar-header">
          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
                  data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <a class="navbar-brand" href="#">Brand</a>
        </div>

        <!-- Collect the nav links, forms, and other content for toggling -->
        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
          <ul class="nav navbar-nav">
            <li class="active">
              <router-link to="/">我的首頁</router-link>
            </li>
            <li>
              <router-link to="/note">我的筆記</router-link>
            </li>
          </ul>

          <ul class="nav navbar-nav navbar-right">
            <li><a href="#">登錄</a></li>
            <li class="dropdown">
            <li><a href="#">注冊</a></li>
          </ul>
        </div><!-- /.navbar-collapse -->
      </div><!-- /.container-fluid -->
    </nav>
    <!--顯示所有路由-->
    {{allRoutes}}
    <!--路由出口-->
    <router-view></router-view>
  </div>
</template>

<script>
  //導入bootstrap
  import 'bootstrap/dist/css/bootstrap.min.css'
  export default {
    name: 'App',
    data:function(){
      return {}
    },
    //計算屬性
    computed:{
      allRoutes:function(){
        // 從Vue實例里面取出所有的路由
        console.log(this.$router.options.routes)
        // return this.$router.options.routes
      }
    }
  }
</script>

<style>

</style>
View Code

刷新頁面,查看console,出現了2個路由

 

使用v-for循環allRoutes

修改App.vue,完整代碼如下:

<template>
  <div id="app">
    <!--導航條-->
    <nav class="navbar navbar-default">
      <div class="container-fluid">
        <!-- Brand and toggle get grouped for better mobile display -->
        <div class="navbar-header">
          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
                  data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <a class="navbar-brand" href="#">Brand</a>
        </div>

        <!-- Collect the nav links, forms, and other content for toggling -->
        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
          <ul class="nav navbar-nav">
            <!--<li class="active">-->
              <!--<router-link to="/">我的首頁</router-link>-->
            <!--</li>-->
            <!--<li>-->
              <!--<router-link to="/note">我的筆記</router-link>-->
            <!--</li>-->
            <!--
          <router-link
            v-for="(route, index) in allRoutes"  : allRoutes是一個計算屬性
            v-bind:to="route.path"               : 取每一項路由的path
            v-bind:key=index                     : for循環vue推薦綁定key,key用來標示for循環的每一項
            tag='li'                             : 告訴router-link渲染的時候 渲染成li標簽
            activeClass='active'                 : 當當前的router-link被選中的時候 添加的 class樣式
            exact                                : 指定路由為嚴格匹配模式,而不是默認的以。。。開頭
            >
            <a>{{route.name}}</a>                : 取每一個路由的name
          </router-link>
         -->
            <router-link
              v-for="(route, index) in allRoutes"
              v-bind:to="route.path"
              v-bind:key=index
              tag='li'
              activeClass='active'
              exact
            >
              <a>{{route.name}}</a>
            </router-link>
          </ul>

          <ul class="nav navbar-nav navbar-right">
            <li><a href="#">登錄</a></li>
            <li class="dropdown">
            <li><a href="#">注冊</a></li>
          </ul>
        </div><!-- /.navbar-collapse -->
      </div><!-- /.container-fluid -->
    </nav>
    <!--路由出口-->
    <router-view></router-view>
  </div>
</template>

<script>
  //導入bootstrap
  import 'bootstrap/dist/css/bootstrap.min.css'
  export default {
    name: 'App',
    data:function(){
      return {}
    },
    //計算屬性
    computed:{
      allRoutes:function(){
        // 從Vue實例里面取出所有的路由
        // console.log(this.$router.options.routes)
        return this.$router.options.routes
      }
    }
  }
</script>

<style>

</style>
View Code

刷新網頁,效果同上!

 

我的筆記面板

點擊我的筆記,下面的內容,是一個面板

使用柵格系統,左側筆記列表為3格,右邊筆記編輯區為9格

訪問 http://127.0.0.1:8080/note

效果如下:

左側列表組件

左側的列表組,是一個組件

在components文件夾下,新建NoteList.vue文件

將Note.vue中的列表組的html代碼剪切過來

NoteList.vue完整代碼如下:

<template>
  <ul class="list-group">
    <li class="list-group-item">Cras justo odio</li>
    <li class="list-group-item">Dapibus ac facilisis in</li>
    <li class="list-group-item">Morbi leo risus</li>
    <li class="list-group-item">Porta ac consectetur ac</li>
    <li class="list-group-item">Vestibulum at eros</li>
  </ul>
</template>

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

<style scoped>

</style>
View Code

修改Note.vue,導入NoteList組件,Note.vue完整代碼如下:

<template>
  <div>
    <div class="container">
      <div class="row">
        <!-- 面板 -->
        <div class="panel panel-info">
          <div class="panel-heading">
            <h3 class="panel-title">我的筆記</h3>
          </div>
          <div class="panel-body">
            <div class="col-md-3">
              <!-- 左邊筆記列表 開始 -->
              <NoteList></NoteList>
              <!-- 左邊筆記列表 結束 -->
            </div>

            <div class="col-md-9">
              <!-- 右邊筆記編輯區 開始 -->
              <div class="note-edit">

              </div>
              <!-- 右邊筆記編輯區 結束 -->
            </div>

          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  //導入NoteList
  import NoteList from '@/components/NoteList.vue'
  export default {
    name: "Note",
    // 加載這個組建的時候 先要去找 NoteList
    components: {
      NoteList,
    }
  }
</script>

<style>
.note-edit {
  height: 600px;
  border: 1px solid grey;
}
</style>
View Code

刷新網頁,效果同上!

 

分離左側列表

每一個li標簽都是組件,在components文件夾下,新建NoteItem.vue文件

<template>
  <div class="list-group-item">
  </div>
</template>

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

<style scoped>

</style>
View Code

修改NoteList.vue,導入NoteItem.vue。NoteList.vue完整代碼如下:

<template>
  <div>
    <div class="list-group">
      <NoteItem
        v-for="(note, index) in NoteList"
        v-bind:name='note'
        v-bind:key="index"
      ></NoteItem>
    </div>
  </div>
</template>



<script>
  import NoteItem from '@/components/NoteItem.vue'
  export default {
    name: 'NoteList',
    components: {
      NoteItem
    },
    data:function(){
      return {
        //聲明數組
        NoteList: [
          '吃飯',
          '睡覺',
          '打豆豆'
        ]
      }
    }
  }
</script>


<style>

</style>
View Code

刷新網頁,效果如下:

 

 父子傳值

 從上圖可以看到,左邊的列表組是空的,需要父子傳值。

父就是NoteList,子就是NoteItem

修改NoteList.vue,增加一個數組,使用for循環遍歷

<template>
  <div>
    <div class="list-group">
      <!--  在子組件聲明 我需要被傳入的參數
      v-for="(note, index) in NoteList"  : NoteList是一個數組,note是數組每一個元素
       v-bind:name=note                  : 子組件聲明,被傳入的參數為name,值為note,也就是數組的元素
      v-bind:key=index                   : for循環vue推薦綁定key,key用來標示for循環的每一項
      -->

      <NoteItem
        v-for="(note, index) in NoteList"
        v-bind:name='note'
        v-bind:key="index"
      ></NoteItem>
    </div>
  </div>
</template>

<script>
  //導入NoteItem組件
  import NoteItem from '@/components/NoteItem.vue'
  export default {
    name: 'NoteList',
    components: {
      NoteItem
    },
    data:function(){
      return {
        //聲明數組
        NoteList: [
          '吃飯',
          '睡覺',
          '打豆豆'
        ]
      }
    }
  }
</script>

<style>
</style>
View Code

修改NoteItem.vue

<template>
  <!--渲染name變量-->
  <div class="list-group-item">{{name}}</div>
</template>

<script>
  export default {
    name: 'NoteItem',
    props: ['name']  // 在子組件聲明 我需要被傳入的參數
  }
</script>

<style>

</style>
View Code

刷新頁面,效果如下:

查看html代碼,和分離之前的代碼,是一致的!

 

右側筆記編輯區

右邊區域,根據柵格系統,平均划分,就可以了。左邊6格,右邊6格

右邊區域也是一個組件,在components目錄下,創建NoteEdit.vue

<template>
  <div class="row">
    <!-- 左邊的 textarea 區域開始 -->
    <div class="col-md-6 height600">
      <div class="input-group">
        <span class="input-group-addon" id="basic-addon1">標題</span>
        <input type="text" class="form-control" placeholder="請輸入標題" aria-describedby="basic-addon1">
      </div>

      <!-- textarea -->
      <textarea class="my-textarea"></textarea>

    </div>
    <!-- 左邊的 textarea 區域結束 -->

    <!-- 右邊的 展示區 區域開始 -->
    <div class="col-md-6 height600">
      <div>
        <button class="btn btn-success">添加</button>
      </div>
      <div class="right-box my-textarea">
      </div>
    </div>
    <!-- 右變的 展示 區域結束 -->
  </div>
</template>


<script>
  // import marked from 'marked'
  export default {
    name: 'NoteEdit',
  }
</script>


<style>
  .my-textarea {
    margin-top: 15px;
    height: 80%;
    width: 100%
  }

  .height600 {
    height: 600px;
  }

  .right-box {
    border: 1px solid grey
  }
</style>
View Code

編輯Note.vue,導入NoteEdit.vue組件,Note.vue完整代碼如下:

<template>
  <div>
    <div class="container">
      <div class="row">
        <!-- 面板 -->
        <div class="panel panel-info">
          <div class="panel-heading">
            <h3 class="panel-title">我的筆記</h3>
          </div>
          <div class="panel-body">
            <div class="col-md-3">
              <!-- 左邊筆記列表 開始 -->
              <NoteList></NoteList>
              <!-- 左邊筆記列表 結束 -->
            </div>

            <div class="col-md-9">
              <!-- 右邊筆記編輯區 開始 -->
              <div class="note-edit">
                <NoteEdit></NoteEdit>
              </div>
              <!-- 右邊筆記編輯區 結束 -->
            </div>

          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  //導入NoteList
  import NoteList from '@/components/NoteList.vue'
  import NoteEdit from '@/components/NoteEdit.vue'
  export default {
    name: "Note",
    // 加載這個組建的時候 先要去找 NoteList
    components: {
      NoteList,
      NoteEdit
    }
  }
</script>

<style>
.note-edit {
  height: 600px;
  /*border: 1px solid grey;*/
}
</style>
View Code

刷新網頁,效果如下:

 

雙向數據綁定

左邊的textarea輸入框的值一旦發現改變,要將數據實時展示在右邊的div中

使用v-model就可以實現

修改NoteEdit.vue

<template>
  <div class="row">
    <!-- 左邊的 textarea 區域開始 -->
    <div class="col-md-6 height600">
      <div class="input-group">
        <span class="input-group-addon" id="basic-addon1">標題</span>
        <input type="text" class="form-control" placeholder="請輸入標題" aria-describedby="basic-addon1">
      </div>

      <!-- textarea -->
      <textarea class="my-textarea"
                v-model="content"
      >

      </textarea>

    </div>
    <!-- 左邊的 textarea 區域結束 -->

    <!-- 右邊的 展示區 區域開始 -->
    <div class="col-md-6 height600">
      <div>
        <button class="btn btn-success">添加</button>
      </div>
      <div class="right-box my-textarea">
        {{content}}
      </div>
    </div>
    <!-- 右變的 展示 區域結束 -->
  </div>
</template>


<script>
  // import marked from 'marked'
  export default {
    name: 'NoteEdit',
    data:function () {
      return {
        content:''
      }
    }
  }
</script>


<style>
  .my-textarea {
    margin-top: 15px;
    height: 80%;
    width: 100%
  }

  .height600 {
    height: 600px;
  }

  .right-box {
    border: 1px solid grey
  }
</style>
View Code

刷新網頁,效果如下:

 

Markdown

Markdown 是一個 Web 上使用的文本到HTML的轉換工具,可以通過簡單、易讀易寫的文本格式生成結構化的HTML文檔。目前 github、Stackoverflow 等網站均支持這種格式。

中文文檔鏈接:

http://www.markdown.cn/

在線編輯器:

https://www.zybuluo.com/mdeditor

 

訪問這個網站,

http://tool.oschina.net/markdown

它能將markdown語法,實時轉換為Html

# 表示h1標簽

```javascript``` 表示javascript代碼

[]() 表示超鏈接

比如: 

 

marked

marked是npm模塊中,專門用來解析markdown語法的

先停止vue項目,安裝marked

-D表示當前項目安裝

E:\python_script\Vue\my-project>npm install marked -D

 出現以下提示,表示安裝成功

+ marked@0.4.0
added 1 package from 1 contributor and audited 8826 packages in 21.209s
found 1 moderate severity vulnerability
  run `npm audit fix` to fix them, or `npm audit` for details

啟動vue項目

E:\python_script\Vue\my-project>npm run dev

 

修改NoteEdit.vue,導入插件marked

<template>
  <div class="row">
    <!-- 左邊的 textarea 區域開始 -->
    <div class="col-md-6 height600">
      <div class="input-group">
        <span class="input-group-addon" id="basic-addon1">標題</span>
        <input type="text" class="form-control" placeholder="請輸入標題" aria-describedby="basic-addon1">
      </div>

      <!-- textarea -->
      <textarea class="my-textarea"
                v-model="content"
      >

      </textarea>

    </div>
    <!-- 左邊的 textarea 區域結束 -->

    <!-- 右邊的 展示區 區域開始 -->
    <div class="col-md-6 height600">
      <div>
        <button class="btn btn-success">添加</button>
      </div>
      <!--展示原始html使用v-html-->
      <div class="right-box my-textarea"
           v-html="markedDownContent"
      >
      </div>
    </div>
    <!-- 右變的 展示 區域結束 -->
  </div>
</template>


<script>
  //導入marked模塊,用來處理makedown語法
  import marked from 'marked'
  export default {
    name: 'NoteEdit',
    data:function () {
      return {
        content:''
      }
    },
    //增加計算屬性
    computed:{
      markedDownContent:function(){
        return marked(this.content)
      }
    }
  }
</script>


<style>
  .my-textarea {
    margin-top: 15px;
    height: 80%;
    width: 100%
  }

  .height600 {
    height: 600px;
  }

  .right-box {
    border: 1px solid grey
  }
</style>
View Code

刷新網頁,輸入幾段makedown語法

#我的家在東北

## 掃得寺內

```python
print("python是世界上最好的語言")
```

- [] 呵呵噠
- [x] 萌萌噠

![很萌的卡通小貓](http://www.gaoxiaogif.com/d/file/4dddbd73cb24eaef339623e28784155f.gif)

 

效果如下:

 

markdown是程序員的必備神器,所以有時間的話,多了解一下markdown的語法!

因為很多程序員都在用它

 

highlight.js

highlight.js是一款輕量級的Web代碼語法高亮庫

使用highlight.js高亮你的代碼,無論是java,js還是php等等語言,都會自動的對關鍵字進行高亮

安裝highlight.js

E:\python_script\Vue\my-project>npm install highlight.js -D

出現以下提示,表示安裝成功

+ highlight.js@9.12.0
added 1 package from 245 contributors and audited 8828 packages in 44.305s
found 1 moderate severity vulnerability
  run `npm audit fix` to fix them, or `npm audit` for details

使用highlight.js

修改main.js,增加一段代碼

//Web代碼語法高亮庫
import hljs from 'highlight.js'
import 'highlight.js/styles/monokai.css' //樣式文件
Vue.directive('highlight',function (el) {
  let blocks = el.querySelectorAll('pre code');
  blocks.forEach((block)=>{
    hljs.highlightBlock(block)
  })
})

注意:

Vue.directive要在實例初始化之前,不然會報錯

main.js完整代碼如下:

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'

Vue.config.productionTip = false
//Web代碼語法高亮庫
import hljs from 'highlight.js'
import 'highlight.js/styles/monokai.css' //樣式文件
Vue.directive('highlight',function (el) {
  let blocks = el.querySelectorAll('pre code');
  blocks.forEach((block)=>{
    hljs.highlightBlock(block)
  })
})
/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})
View Code

 

修改NoteEdit.vue,增加v-highlight即可

<div class="right-box my-textarea" v-html="markedDownContent" v-highlight>

NoteEdit.vue完整代碼如下

<template>
  <div class="row">
    <!-- 左邊的 textarea 區域開始 -->
    <div class="col-md-6 height600">
      <div class="input-group">
        <span class="input-group-addon" id="basic-addon1">標題</span>
        <input type="text" class="form-control" placeholder="請輸入標題" aria-describedby="basic-addon1">
      </div>

      <!-- textarea -->
      <textarea class="my-textarea"
                v-model="content"
      >

      </textarea>

    </div>
    <!-- 左邊的 textarea 區域結束 -->

    <!-- 右邊的 展示區 區域開始 -->
    <div class="col-md-6 height600">
      <div>
        <button class="btn btn-success">添加</button>
      </div>
      <!--展示原始html使用v-html-->
      <div class="right-box my-textarea"
           v-html="markedDownContent"
           v-highlight
      >
      </div>
    </div>
    <!-- 右變的 展示 區域結束 -->
  </div>
</template>


<script>
  //導入marked模塊,用來處理makedown語法
  import marked from 'marked'

  export default {
    name: 'NoteEdit',
    data:function () {
      return {
        content:''
      }
    },
    //增加計算屬性
    computed:{
      markedDownContent:function(){
        return marked(this.content)
      }
    }
  }
</script>


<style>
  .my-textarea {
    margin-top: 15px;
    height: 80%;
    width: 100%
  }

  .height600 {
    height: 600px;
  }

  .right-box {
    border: 1px solid grey
  }
</style>
View Code

刷新網頁,增加一段python和javascript代碼

```python
class Student(object):
    def __init__(self, name, age, score):
        self.name = name
        self.age = age
        self.score = score

    def get_name(self):  # 獲取學生的姓名
        return self.name

    def get_age(self):  # 獲取學生的年齡
        return self.age

    def get_course(self):  # 返回3門科目中最高的分數
        return '{}\n{}\n{}'.format(self.name,self.age,max(self.score))
```

```javascript
var name = "abc";
console.log(name);
```
View Code

效果如下:

 

 
 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM