---
# System prepended metadata

title: 將資料加入Vue Data (1-2)
tags: ['1. 快速入門 Vue.js ', Vue]

---

# 將資料加入Vue Data (1-2)
###### tags: `Vue`、`1. 快速入門 Vue.js `
2022.2.28

&emsp;&emsp;加入外部資料product，然後將輸入資料送進資料中。
```
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Document</title>
    <script src="https://unpkg.com/vue@3"></script>
</head>
<body>

<div id="app">
    <form>
        <div class="mb-3">
          <label for="productName" class="form-label">產品名稱</label>
          <input type="text" id="productName"
            class="form-control"
            v-model="temp.name"
          >
        </div>
        <div class="mb-3">
          <img :src="temp.imageUrl" class="img-fluid d-block" alt="" width="300">
          <label for="productImage"
          class="form-label">產品圖片</label>
          <input type="text" id="productImage"
            class="form-control"
            v-model="temp.imageUrl"
          >
        </div>
        <button type="button"
        class="btn btn-secondary"
        v-on:click="confirmEdit">更新</button>
      </form>
</div>

<script>
const products = [{
  id: '1',
  imageUrl: 'https://images.unsplash.com/photo-1516906571665-49af58989c4e?ixlib=rb-1.2.1&ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&auto=format&fit=crop&w=300&q=80',
  name: 'MacBook Pro',
  onStock: false,
},{
  id: '2',
  imageUrl: 'https://images.unsplash.com/photo-1512499617640-c74ae3a79d37?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=80',
  name: 'iPhone',
  onStock: false,
}];
const App={
    data(){
        return{
            products:[],
            temp:{
                name:'Oldmoon',
                imageUrl:'https://images.unsplash.com/photo-1602526430780-782d6b1783fa?ixid=MXwxMjA3fDF8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1350&q=80'
            }
        }
    },
    methods:{
        confirmEdit(){
            this.temp.id = new Date().getTime(); //新增流水號(為了與products格式一致)
            this.temp.onStock = false; //(為了與products格式一致)
            this.products.push(this.temp); //將temp(輸入資料)新增至product
            this.temp = {}; //清空temp
        }
    },
    created(){
        this.products = products; //引入product資料
    }
}
Vue.createApp(App).mount("#app");
</script>
</body>
<link rel="stylesheet" href="/stylesheets/all.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css">
</html>
```