Slog17_支配vue框架模版語法之v-for

  • ArthurSlog
  • SLog-17
  • Year·1
  • Guangzhou·China
  • July 19th 2018

關注微信公衆號「ArthurSlog」

實際上 結果是最重要的 根本沒有人在意你的過程 甚至根本就沒有人在意你html


開發環境MacOS(High Sierra 10.13.5)

須要的信息和信息源:

  1. v-text
  2. v-html
  3. v-show
  4. v-if
  5. v-else
  6. v-else-if
  7. v-for
  8. v-on
  9. v-bind
  10. v-model
  11. v-pre
  12. v-cload
  13. v-once
  • vue.js 的模版指令,與編程語言的 「關鍵字」 或者 「保留字」 有點類似,例如 if(判斷語句關鍵字)、for(循環語句關鍵字)

開始編碼

  • 首先,搭起靜態服務器,先切換至桌面路徑
cd ~/Desktop
  • 建立一個文件夾node_vue_directive_learningload
mkdir node_vue_directive_learningload
  • 切換路徑到新建的文件夾下
cd node_vue_directive_learningload
  • 使用npm初始化node環境,一路enter鍵完成初始化
npm init
  • 使用npm安裝koa和koa-static
sudo npm install koa koa-static

index.jsvue

const serve = require('koa-static');
const Koa = require('koa');
const app = new Koa();

// $ GET /package.json
app.use(serve('.'));

app.listen(3000);

console.log('listening on port 3000');

index.htmlnode

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>ArthurSlog</title>
</head>

<body>

    <h1>The static web server by ArthurSlog</h1>

</body>

</html>
  • 接下來,咱們來根據使用場景,來編寫 vue.js 模版指令代碼

v-for.htmlgit

<!DOCTYPE html>
<html>
    <head>
    <meta charset="utf-8">
    <!-- 開發環境版本,包含了有幫助的命令行警告 -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <title>ArthurSlog</title>
    </head>
    <body>
        <div id="app">
            <div v-for="item in items">
            {{ item.text }}
            </div>
        </div>
        <script>
        new Vue({
            el: '#app',
            data: {
                items: [
                    {id: 0, text: 'Hello ArthurSlog~ id: 0' + '\n'},
                    {id: 1, text: 'Hello ArthurSlog~ id: 1' + '\n'},
                    {id: 2, text: 'Hello ArthurSlog~ id: 2' + '\n'}
                ]
            }
        })
        </script>
    </body>
</html>
  • 如今你能夠打開瀏覽器,在地址欄輸入 127.0.0.1:3000/v-for.html,你會看到:
Hello ArthurSlog~ id: 0
Hello ArthurSlog~ id: 1
Hello ArthurSlog~ id: 2
  • 這裏注意到,咱們建立了一個對象 「items」,他是一個數組,裏面存放了三個對象,每一個對象擁有兩個屬性 「id」 和 「text」,他們的值都不同:
items: [
    {id: 0, text: 'Hello ArthurSlog~ id: 0' + '\n'},
    {id: 1, text: 'Hello ArthurSlog~ id: 1' + '\n'},
    {id: 2, text: 'Hello ArthurSlog~ id: 2' + '\n'}
]
  • 看到模版語法裏, 「item」 是一個臨時的對象,這個名字隨便定,只是臨時使用的,「item in items」 這樣的語法,意思就是在 「items」 這個對象中,按順序一個一個取出裏面的對象,而後,每一次取出對象的時候,打印出對象的 「text」 屬性的值:
<div v-for="item in items">
{{ item.text }}
</div>
  • 至此,咱們把 vue模版指令 v-for 介紹了一遍,更多使用方法和信息,請參考 vue官方手冊

歡迎關注個人微信公衆號 ArthurSlog

ArthurSlog

若是你喜歡個人文章 歡迎點贊 留言

謝謝

相關文章
相關標籤/搜索