【发布时间】:2021-02-20 22:17:41
【问题描述】:
这是我在这里的第一篇文章!只是需要一些小的帮助来解决问题。谢谢!
我刚开始学习 vue.js,我正在尝试让我的第二个组件模板显示在页面上。出于某种原因,vue 没有渲染我的第二个组件,只有第一个。我认为<education :data='data' /> 的索引文件中有问题。我需要创建一个不同的<div id='app'> 并将第二个组件放入其中吗?
app.js:
// Fetch handler
function fetchData(url) {
return fetch(url)
.then(checkStatus)
.then(res => res.json())
.catch(error => console.log('Error retrieving data', error))
}
// Response error handler
function checkStatus(res) {
if(res.ok) {
return Promise.resolve(res);
} else {
return Promise.reject(new Error(res.statusText));
}
}
(() => {
// Define components.
Vue.component('contact-info', {
props: ['data'],
template: `
<div>
<img v-bind:src='data.photo'>
<h1>{{ data.name }}</h1>
<p>{{ data.email }}</p><p>{{ data.phone }}</p>
<p v-if='data'>{{ data.links[0] }}</p><p v-if='data'>{{ data.links[1] }}</p>
</div>
`
});
Vue.component('education', {
props: ['data'],
template: `
<div>
<h3>Education</h3>
<div>
<h2></h2>
<p></p>
<p></p>
<div>
<div>
`
});
// Instantiate the app.
const app = new Vue({
el: '#app',
data() {
return {
data: ''
}
},
mounted() {
fetchData('https://wip.journeygroup.com/intern-api/joshbryant.json')
.then(jsonData => (this.data = jsonData))
}
});
})();
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Resume • Josh Bryant</title>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://fonts.googleapis.com/css2?family=Work+Sans:wght@400;600;800&display=swap" rel="stylesheet">
<link rel="stylesheet" href="./css/main.css">
</head>
<body>
<div id="app">
<contact-info :data='data' />
<education :data='data' />
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script src="./app/main.js"></script>
</body>
</html>
【问题讨论】:
-
不确定这是否是原因,但您不应该将道具命名为
data,因为 data 是 Vue 实例中的特殊对象/函数。将其命名为config、myData等...另一个细节:fetchData是什么?它在哪里定义/导入? -
抱歉,fetchData 是在 vue 函数之上定义的。它基本上只是一个获取错误处理程序。
标签: javascript vue.js templates components