先说明一下
我用轻前端 Vue 的目的,不是把整个网站都改用轻前端,而是为了把复杂的 js 取值、给值的逻辑交由 Vue Model Binding 的机制处理,进而省下语法 !
在 Vue 这个部份来说,我还在学习中,所以文章内容不会提到该怎麽写 Vue,但我会使用 Composition API
另外,debug 时,记得持续开启 chrome DevTools,看看 console 是否会报错 !
Controller 内的
Get Action :
为了让 Vue 起始能 Binding 成功,进入 Get 页面时,一并给定 ViewModel 预设值 !
[HttpGet]
public IActionResult Case01()
{
return View(new ViewModel());
}
Post Action :
只要是 ajax 所指定的 Action,该 Action 的 Route 都会改为 api 开头
ajax Action 的部份,因为需要改成 json 格式,所以从原本的 FromForm
改成 FromBody
[HttpPost, Route("api/[controller]/[action]")]
public IActionResult PostCase01([FromBody]ViewModel vm)
{
return Ok(vm);
}
View :
改用轻前端,等於前後端分离,所以前端栏位名称都要手动给定 !
我会切开 C# 与 js / vue 的 coding style
Razor 的语法的影响限制
因为 Vue 的 Model Binding 是针对 js object,所以 ajax request content type 全部改为 json 格式
js 套件的引用,我统一放在 _Layout.cshtml 中
新增 JsonHelper,提供 ToJson() Extension Method !
public static class JsonHelper
{
public static string ToJson<T>(this T t, bool isCamelCase = true)
{
var jsonSerializerOptions = new JsonSerializerOptions();
if (isCamelCase)
{
jsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
}
return JsonSerializer.Serialize(t, jsonSerializerOptions);
}
}
内容
<div id="app" v-cloak>
<form autocomplete="off"
v-on:submit.prevent="submit_form">
<p>
<label for="id">编号:</label>
<input type="number"
step="1"
min="0"
id="id"
v-model.number="vue_model.id" />
</p>
<p>
<label for="name">姓名:</label>
<input type="text"
id="name"
v-model="vue_model.name" />
</p>
<p>
<button type="submit">送出</button>
</p>
</form>
<p>
<a v-bind:href="prev_url">回上一层</a>
</p>
</div>
@section Scripts
{
<script>
const app = createApp({
setup(){
const post_url = '@Url.Action("PostCase01")';
const prev_url = '@Url.Action("Index")';
const vue_model = ref(@Html.Raw(Model.ToJson()));
const submit_form = function() {
fetch(post_url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(vue_model.value),
})
.then(response => response.json())
.then(data => {
vue_model.value = data;
});
}
return {
post_url,
prev_url,
vue_model,
submit_form,
}
}
});
const vm = app.mount('#app');
</script>
}
执行网站後,可以看出 ajax 打回後端,取回时,直接把资料放回 js object 就好 !
换句话说,不需要从 html 把 html 控制项的 value 取出,等後端处理完毕後,再放回 html 控制项中 !
整个清爽许多了 !!
这篇先到这里,下一篇来看 复杂型别 object + collection
!
Vue:还记得第10天时,我们才刚认识Vue CLI,但你还记得我的介面吗? 接着,我们试试看这个指...
为什麽会用mongoDB 一开始决定要用 SQL 或 NoSQL时,因为考虑到 不用定义 schem...
前情提要 艾草:「this is a book。」 「你在做什麽呀?」 艾草:「练习你的语言呀。」 ...
retrofit kotlin可以使用retrofit结合coroutines去实现取得api的方法...
各位板上前辈们好 最近想架设一个网站 放上公司的产品介绍、简介、基本资料 客户主要是外国消费者,我们...