[英]Get dynamic data from PHP to Vue.js
我正在使用PHP(CodeIgniter)渲染使用vue cli構建的頁面。
通常,如果我想將值從php傳遞到javascript,我會執行以下操作:
var page = '<?php echo $page ?>';
但是由於該頁面是使用vue構建的,因此所有js都已縮小,這是不可能的。 我需要一個替代解決方案來獲取從php發送的vue中的變量。
試試這個:這里js變量msg2打印php變量$ test value =“ Chris”
<html>
<head>
<title>Example</title>
<script type = "text/javascript" src = "https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
</head>
<body>
<div id = "intro" style = "text-align:center;">
<h1>{{ message }}</h1>
<p>{{ msg2 }}</p>
<?php
$test = "Chris";
?>
</div>
<script type = "text/javascript">
var vue_det = new Vue({
el: '#intro',
data: {
message: 'My first VueJS Task',
msg2: "<?php echo $test ?>"
}
});
</script>
</body>
</html>
您應該放棄通過var page = '<?php echo $page ?>';
的想法var page = '<?php echo $page ?>';
進入JS。
1.檢查您的路由 -我假設您仍然具有帶有邏輯的PHP頁面,並且Vue在單獨的Controller上。
$route['default_controller'] = 'Home';
// Create a new controller with the name Vue before adding the routes.
$route['vue'] = 'Vue'; // default page
$route['vue/(:any)'] = 'Vue/$1'; // vue/with-any-passing/value/you/want
2.控制器:Vue.php
<?php
class Vue extends CI_Controller {
public function index( $uri_for_vue = '' )
{
$vueSetup = array(
'settings' => array(
'vueURL'=> $uri_for_vue
)
);
$this->load->view('vueView', $vueSetup);
}
}
3.查看:vueView.php
<html>
<head>
<title>vue page</title>
<script type = "text/javascript" src = "https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
</head>
<body>
<div id = "intro" style = "text-align:center;">
<h1>{{ message }}</h1>
<p>{{ msg2 }}</p>
<?php
$test = "Chris";
?>
</div>
<script id='vue-elem' data-vue='<?php echo json_encode($settings)?>' type = "text/javascript"></script>
<script type = "text/javascript">
var vueElem = document.getElementById('vue-elem');
var vueSettings = JSON.parse(vueElem.getAttribute("data-vue"));
// you may want to remove the element from html after it's contents is loaded in js, or reset the
// vueElem .setAttribute("data-vue", "{}");
// you will want to add this line in the minified version so vue can self-load
var page = vueSettings.vueURL;
console.log('page url', page );
// now you can load vue
</script>
</body>
</html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.