Текущий код изменяет шрифт для всех строк по сравнению с определенной строкой:
Vue.component('blog-post', {
props: ['post'],
template: `
<div class = "blog-post row">
<h3 class = "cell"> {{ post.title }}</h3>
<button @click = "$emit('enlarge-text')">Enlarge text</button>
<div v-html = "post.content" class = "cell"></div>
</div>
`,
});
new Vue({
el : '#blog-post-demo',
data : {
posts : [
{id: 1, title : 'My Journey to Africa', content : 'I am the post'},
{id: 2, title : 'My Journey to America', content : 'I am the post'},
{id: 3, title : 'My Journey to Antartica', content : 'I am the post'},
{id: 4, title : 'My Journey to Asia', content : 'I am the post'},
],
postFontSize : 1,
}
});
.row {
background-color: cyan;
}
.cell {
background-color: antiquewhite;
}
<script src = "https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
<div id = "blog-post-demo">
<blog-post v-for = "post in posts" :post = "post" :key = "post.id" :style = "{fontSize : postFontSize + 'em'}" @enlarge-text = "postFontSize += 0.1"></blog-post>
</div>
Как я могу просто манипулировать определенной строкой, одной строкой, обновлять размер шрифта одной строки по сравнению со всеми строками?
Пробовал следующее, но это не сработало:
Vue.component('blog-post', {
props: ['post'],
template: `
<div class = "blog-post row" :style = "{fontSize : postFontSize + 'em'}" @enlarge-text = "postFontSize += 0.1">
<h3 class = "cell">{{ post.title }}</h3>
<button @click = "$emit('enlarge-text')">Enlarge text</button>
<div v-html = "post.content" class = "cell"></div>
</div>
`,
});
new Vue({
el : '#blog-post-demo',
data : {
posts : [
{id: 1, title : 'My Journey to Africa', content : 'I am the post'},
{id: 2, title : 'My Journey to America', content : 'I am the post'},
{id: 3, title : 'My Journey to Antartica', content : 'I am the post'},
{id: 4, title : 'My Journey to Asia', content : 'I am the post'},
],
postFontSize : 1,
}
})
.row {
background-color: cyan;
}
.cell {
background-color: antiquewhite;
}
<script src = "https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
<div id = "blog-post-demo">
<blog-post v-for = "post in posts" :post = "post" :key = "post.id"></blog-post>
</div>
Если вы хотите обновить только 1 строку, postFontSize
должны быть локальными данными компонента blog-post
.
<!DOCTYPE html>
<html>
<head>
<title>My first Vue app</title>
<script src = "https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<style>
.row {
background-color: cyan;
}
.cell {
background-color: antiquewhite;
}
</style>
</head>
<body>
<div id = "blog-post-demo">
<blog-post v-for = "post in posts" :post = "post" :key = "post.id"></blog-post>
</div>
<script>
Vue.component('blog-post', {
props: ['post'],
template: `
<div class = "blog-post row" :style = "{fontSize : postFontSize + 'em'}">
<h3 class = "cell"> {{ post.title }}</h3>
<button @click = "postFontSize += 0.1">Enlarge text</button>
<div v-html = "post.content" class = "cell"></div>
</div>`,
data() {
return {
postFontSize : 1
}
}
})
new Vue({
el : '#blog-post-demo',
data : {
posts : [
{id: 1, title : 'My Journey to Africa', content : 'I am the post'},
{id: 2, title : 'My Journey to America', content : 'I am the post'},
{id: 3, title : 'My Journey to Antartica', content : 'I am the post'},
{id: 4, title : 'My Journey to Asia', content : 'I am the post'},
]
}
})
</script>
</body>
</html>
Причина, по которой ваш первый фрагмент кода не работает, заключается в том, что вы поместили переменную postFontSize
в его родительский компонент. Вот почему все дочерние компоненты будут использовать одну и ту же переменную, а это означает, что одно изменение в переменной повлияет на каждого дочернего компонента.
Чтобы решить эту проблему, просто переместите все переменные, связанные с компонентом blog-post
, в компонент blog-post
(а не в его родительский компонент).
Сюда входят postFontSize
, @click
метод и :style
декларация:
Vue.component('blog-post', {
template: `
<div class = "blog-post row" :style = "{ fontSize: postFontSize + 'em' }">
<h3 class = "cell">{{ post.title }}</h3>
<button @click = "enlargeText">Enlarge text</button>
<div v-html = "post.content" class = "cell"></div>
</div>
`,
props: ['post'],
data: function(){
return {
postFontSize: 1
}
},
methods: {
enlargeText: function(){
this.postFontSize += 0.1;
}
}
});
new Vue({
el : '#blog-post-demo',
data : {
posts : [
{id: 1, title : 'My Journey to Africa', content : 'I am the post'},
{id: 2, title : 'My Journey to America', content : 'I am the post'},
{id: 3, title : 'My Journey to Antartica', content : 'I am the post'},
{id: 4, title : 'My Journey to Asia', content : 'I am the post'},
]
}
});
.row {
background-color: cyan;
}
.cell {
background-color: antiquewhite;
}
<script src = "https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
<div id = "blog-post-demo">
<blog-post v-for = "post in posts" :post = "post" :key = "post.id"></blog-post>
</div>
В чем разница между наличием postFontSize
в переменной data
внутри new Vue
и data
внутри компонента?
@RobertRocha Думайте о new Vue
как о глобальной области видимости в Vue. Когда вы меняете глобальную переменную, это затрагивает все, что зависит от той же самой глобальной переменной в этой области, потому что, по сути, зависит только от одной переменной. Когда вы помещаете эту переменную внутрь компонента (локальная область видимости), каждый компонент зависит от своей собственной переменной. Таким образом, изменения за пределами локальной области не повлияют на компонент.
В чем разница между наличием
postFontSize
в переменнойdata
внутриnew Vue
иdata
внутри компонента?