我目前正在将使用VueJS的Laravel应用迁移到SvelteJS(用Svelte替换Vue部分)。
借助VueJS,我可以轻松地将道具发送到页面上安装的组件:
<users :name="John Doe"></users>
然后在组件中访问名称prop。
在Svelte中,我只能传递道具并在嵌套时在组件中访问它们。
应用程序组件:我可以引用用户组件并发送道具
<h1>Hello {name} - { count }</h1>
<h1>Employees of VONIDI</h1>
<Users villain="Jean Claude Van Damme" hero={employees} />
<ul>
{#each employees as employee}
<li><a target="_blank" href={employee}>{employee}</a></li>
{:else}
<li>No employee :(</li>
{/each}
</ul>
<form on:submit="processForm(event)">
<input bind:value=form.name type=text>
<input ref:date id="date" bind:value=form.date type=text>
<label>
<input type='checkbox' bind:group='form.colours' value='red'>
red
</label>
<label>
<input type='checkbox' bind:group='form.colours' value='blue'>
blue
</label>
<button type=submit>Say hello</button>
</form>
<button on:click="set({ count: count + 1 })"> +1 </button>
<button on:click="set({ count: count - 1 })"> -1 </button>
<style>
h1 {
color: purple;
}
</style>
<script type="text/javascript">
import axios from 'axios';
import flatpickr from 'flatpickr';
import "flatpickr/dist/themes/dark.css";
export default {
components: {
Users: './users.svelte'
},
data() {
return {
count: 0,
name: 'WORLD',
employees: [],
form: {
name: '',
colours: [],
date: ''
}
};
},
oncreate() {
console.log('Created TAG!');
this.loadStudents();
console.log(this.options);
flatpickr('#date', {
mode: "range",
minDate: "today",
dateFormat: "Y-m-d",
disable: [
function(date) {
// disable every multiple of 8
return !(date.getDate() % 8);
}
]
});
},
methods: {
getStudents() {
return axios.get('/employees');
},
async loadStudents() {
let response = await this.getStudents();
this.set({
employees: response.data
});
const emp = this.get();
console.log(emp);
},
processForm(event) {
event.preventDefault();
const tagline = this.get();
console.log(tagline);
alert(`Hello ${tagline.form.name}!`);
}
}
};
</script>
用户组件:
<h4>Employees from User Tag: {hero}</h4>
<h2>Villain: { villain }</h2>
<script>
export default {
tag: 'users-tag',
oncreate() {
console.log('User component created!')
console.log( this.get() )
}
};
</script>
但是我不知道如何将道具发送到未嵌套的组件,即:在独立的用户组件中,我无法发送道具。
<users villain="Jean Claude Van Damme" hero="One"></users>
我总是会得到prop值的不确定错误。关于如何实现此目标的任何想法?
谢谢
答案 0 :(得分:1)
如果我理解正确,那么您正在尝试在组件初始化后修改其中的数据。
When you initialize the component you do something like:
var mything= new Thing({
target: someplace,
data: {text:"some text",status:" works good"}
});
稍后,如果您需要更改数据,可以执行以下操作:
mything.set({text:"new text");