18. Interpolation and Data Binding - daniel-qa/Vue GitHub Wiki

18. Interpolation and Data Binding

data()

它基本上意味着存储在data属性中的值是一个函数。

现在, 这个函数应该做什么?

它应该做一件非常简单但重要的事情。

它会传回物件, 而且永远是物件。

data() 裡,可以儲存任何對程式有意義的內容

const app = Vue.CreateApp()({
    data(){
        return{

        };
    }

});
  • 插值和 data() 屬性
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vue Basics</title>
    <link
      href="https://fonts.googleapis.com/css2?family=Jost:wght@400;700&display=swap"
      rel="stylesheet"
    />
    <link rel="stylesheet" href="styles.css" />
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <script src="app.js" defer></script>
  </head>
  <body>
    <header>
      <h1>Vue Course Goals</h1>
    </header>
    <section id="user-goal">
      <h2>My Course Goal</h2>
      <p>{{ courseGoal }}</p>
    </section>
  </body>
</html>
const app = Vue.createApp({
    data() {
        return {
            courseGoal: 'Finish the course and learn Vue!'
        };
    }
});

app.mount('#user-goal');

  • v-bind
 <p>Learn more <a v-bind:href="vueLink">about Vue</a>.</p>
    data() {
        return {
            courseGoal: 'Finish the course and learn Vue!',
            vueLink: 'https://vuejs.org/'
        };
    }
}

插值裡,可以寫簡單的 javascript

{{ 1 + 1 }}
  • method

outputGoal() ,會隨機輸出字串

<p>{{ outputGoal() }}</p>
const app = Vue.createApp({
    data() {
        return {
            courseGoal: 'Finish the course and learn Vue!',
            vueLink: 'https://vuejs.org/'
        };
    },
    methods:{
        outputGoal(){
            const randomNumber = Math.random();
            if(randomNumber < 0.5){
                return 'Learn Vue!';
            }else{
                return 'Master Vue!';
            }
        }
    }
});

app.mount('#user-goal');
  • this

可以取得 data() 中的數據

return this.courseGoalA;

const app = Vue.createApp({
    data() {
        return {
            courseGoalA: 'Finish the course and learn Vue!',
            courseGoalB: 'Master Vue and build amazing apps!',
            vueLink: 'https://vuejs.org/'
        };
    },
    methods:{
        outputGoal(){
            const randomNumber = Math.random();
            if(randomNumber < 0.5){
                return this.courseGoalA;
            }else{
                return 'Master Vue!';
            }
        }
    }
});
⚠️ **GitHub.com Fallback** ⚠️